Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a Thread class

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to create Thread class". In daily operation, I believe many people have doubts about how to create Thread class. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts about "how to create Thread class". Next, please follow the editor to study!

The basic concept of threading

A Process is a running activity of a program with a certain independent function on a certain data set, and it is an independent unit for resource allocation and scheduling of the system. A program is just an ordered collection of instructions, which does not have any meaning to run, but a static entity. The process is different, it is the execution of the program on a data set, it is a dynamic entity. It is created because it is created, runs because of scheduling, is in a waiting state because of waiting for resources or events, and is cancelled because of completing the task, which reflects the whole dynamic process of a program running on a certain data set.

A Thread is an entity of a process and the basic unit of CPU scheduling and dispatching. Threads cannot execute independently and must be stored in the application, which provides multiple thread execution control.

The relationship between the thread and the process is that the thread belongs to the process, the thread runs in the process space, and the threads generated by the same process share the same memory space. When the process exits, the threads generated by the process will be forced to exit and clear. A thread can share all the resources owned by a process with other threads belonging to the same process, but it basically does not own system resources, only a bit of information that is essential to running (such as program counters, a set of registers, and stacks).

To understand the concept of multithreading, we must first understand its benefits. Assuming that there is no concept of threading, then when an application is executing, if multiple branch programs are needed to process data at the same time, you need to start another process.

For example, if you want to execute the main method of multiple JAVA files at the same time, isn't it necessary to start multiple JAVA virtual machines? Each virtual machine has to allocate a piece of memory, counters, registers, etc., so that the operating system will not like it if it consumes system resources. In order to be able to run multiple branch programs at the same time without making a big fight, so there is the concept of thread, thread opening is relatively easy, it is completed in the process. The operating system will not allocate another piece of memory, data area, etc., so all threads in a process share memory.

Switching between threads

Because the current operating system supports multi-process and multi-thread. (previous computers such as DOS systems do not support multiple processes, that is, only one program can be run at a time.) the number of CPU is always limited, although with the development of hardware, the number of CPU in a computer becomes more and more, but it can never reach the extent that each program is assigned a CPU. Therefore, the operating system must allocate the limited CPU resources to the application reasonably. In other words, if multiple programs grab a CPU, everyone will take turns to execute, and there will be switching between processes, as well as switching between multiple threads. Switching between threads is less expensive than a process. So it's considered lightweight.

How do I start a thread? Two methods

A Thread class is provided in JDK, which can help us start an extra thread in the java program. Why is it extra? Because the main function is also a thread, it is called the main thread of the program.

To start a thread, of course you need to create an instance of the Thread class:

Thread t = new Thread () {

@ Override

Publicvoid run () {

/ / TODO Auto-generated method stub

}

}

Thread t = new Thread (new Runnable () {

@ Override

Publicvoid run () {

/ / TODO Auto-generated method stub

}

});

T.start ()

The Thread class takes a parameter, an object of type Runnable, and looks at the API documentation to see that Runnable is an interface and defines a run () method.

You only need to customize a class to implement the interface and write the code you need to execute in the run method. In addition, another way to start a thread is to customize a class that inherits the Thread class. Looking at the API document, we can see that the Thread class itself implements the Runnable interface, so we can also rewrite the run method in the Thread class.

The thread's sleep () method

Thread sleep, sleep does not occupy CPU resources, can be interrupted by the interrupt () method, the thread will throw InterruptedException after the interruption, the thread in the sleep process, the synchronization lock will not be released.

The join () method of the thread (merge threads)

When a thread calls the join method, the thread is merged with the current thread, waiting for the thread to finish execution before continuing, and join also has an overloaded method with parameters that can specify how many milliseconds to wait.

If you execute t.join (2000) in the main method, the main thread waits for the thread t for two seconds before running.

The yield () method of the thread (manually switching threads)

This method makes the thread give up the CPU resource and change from the running state to the ready state. At this point, the operating system reassigns CPU to the thread. And the yield () method can only give threads of the same priority a chance to execute.

Yield does not cause thread blocking, so there is no guarantee that CPU will be given up to another thread. Assuming that a thread has the highest priority, the yield method is called at this time, and the operating system most likely selects the thread again and allocates CPU. It's like an eldest person giving up his eldest title for everyone to re-elect the eldest. This kind of hypocritical elegance will not be liked by everyone.

Status and priority of the thread

The priority of the thread is expressed as a number, and from 1 to 10 indicates that the priority is from low to high. When scheduling CPU, the operating system will give priority to assigning CPU to high-priority threads to run.

Synchronization of threads

Bank withdrawal, concurrent operation of data

ATM Bank counter Database query request 1 returns result 1 withdrawal request 1 query request 2 returns result 2 withdrawal request 2

When both query request 1 and query request 2 are executed, if the result 1 and result 2 returned by the database have a balance of 10000. At this time, the bank counter issued a withdrawal request 1, withdrawing 8000 yuan, because the balance is 10000 > 8000, so the request is allowed, the balance should be 2000. The withdrawal request is eventually converted to an update operation of DATABASE, updating the balance to 2000. At the same time, ATM issued a withdrawal request 2, withdrawing 8000 yuan, because the balance is 10000 > 8000, so the request is allowed again, the balance should be 2000. Eventually, the withdrawal request is also converted to a database update operation, updating the balance to 2000. At this time, there was a serious problem. A total of 16000 was taken away, but there was still 2000 left in the database.

This is a very classic security problem caused by multithreading. In order to solve this problem, we introduce the concept of synchronous lock.

The concept of synchronization lock: the so-called synchronization refers to step-by-step execution. If the operation is performed at the same time, we call it asynchronous or concurrent. When a thread executes a request, if a row of records in the database is locked, other threads cannot operate on the database at this time and must wait for the first thread to finish. This avoids the problems caused by manipulating one row of records at the same time.

Thread safety problem: when multiple threads access the same data, if each thread modifies the data, the value of the data becomes difficult to determine. A variable whose value is uncertain may cause catastrophic errors in the whole system, so this is something we never want to see. Therefore, there are two ways to solve thread safety problems:

First, if a class needs to be accessed by multiple threads, never add any member variables to prevent data confusion caused by multi-threads sharing a piece of data.

Second, thread synchronization is used to access the same data.

In order to solve the problem of thread safety, JAVA also introduces the mechanism of synchronous lock: Synchronized keyword.

The JVM specification reads as follows:

"in JVM, each object and class is logically associated with a monitor."

"to achieve the exclusive monitoring capabilities of the monitor, JVM associates a lock for each object and class."

This is also called mutex, which means that multiple threads acquire the lock of the object at the same time, and the monitor is responsible for supervising the lock of the object, allowing only one thread to acquire the lock at a time. Using this method, multiple threads can execute sequentially synchronously.

Four uses of the Synchronized keyword:

Public synchronized void someMethod () {

/ / method body

}

The method is declared to be a synchronous method, that is, the execution of the method must obtain the current object lock

Public synchronized static void someMethod () {

/ / method body

}

The method is declared as a synchronous method, and because the method is static, it cannot obtain the lock of the current object, so this method acquires the class object lock of the current class, that is, the execution of the method must first obtain the class object lock of the class.

Public static void someMethod () {

Synchronized (SynTest.class) {

/ / method body

}

}

This method contains a synchronous code block, which means that the class object lock of the current class must be acquired before executing the code of the syn statement block.

Public void someMethod () {

Synchronized (this) {

/ / method body

}

}

This method contains a synchronous code block, that is, the current object lock must be acquired before executing the code of the syn statement block.

Synchronized is used to specify synchronization blocks, and it can only lock objects, not basic data types.

Thread deadlock

A deadlock, a lock that can never be unlocked. We should try our best to avoid this problem in program development.

When thread 1 locks resource An and thread 2 locks resource B, thread 1 must get the lock of resource B before execution ends, thus releasing resource A. Thread 2 must get resource An in order to release resource B.

With such a deadlock, the two threads cannot end, resulting in a deadlock.

Example program about deadlock:

Publicclass DeadLock {

Publicstaticvoid main (String [] args) {

Thread T1 = new Thread (new DL (true))

Thread T2 = new Thread (new DL (false))

T1.start (); t2.start ()

}

}

Class DL implements Runnable {

Static Object lockX = new Object ()

Static Object lockY = new Object ()

Booleanflag = true

Public DL (boolean flag) {

This.flag = flag

}

@ Override

Publicvoid run () {

If (flag) {

Synchronized (lockX) {

Try {

Thread.sleep (2000)

} catch (InterruptedException e) {

E.printStackTrace ()

}

Synchronized (lockY) {/ / blocking

System.out.println ("end of execution")

}

}

} else {

Synchronized (lockY) {

Try {

Thread.sleep (2000)

} catch (InterruptedException e) {

E.printStackTrace ()

}

Synchronized (lockX) {

System.out.println ("end of execution")

}

}

}

}

}

At this point, the study on "how to create a Thread class" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report