Home >Java >javaTutorial >Java concurrent programming: How to use the Thread class?

Java concurrent programming: How to use the Thread class?

零下一度
零下一度Original
2017-06-23 09:16:042019browse
Java Concurrent Programming: Use of Thread Class
 
The following is the table of contents outline of this article:
 1. Thread status
 II.Context Switch
3. Methods in the Thread class
 
Reprinted from:
 

1. Thread status

 Threads go through several states from creation to final death. Generally speaking, threads include the following states: creation (new), ready (runnable), running (running), blocked (blocked), time waiting, waiting, and death (dead).
 
The picture below describes the state of a thread from creation to death:

In some tutorials, blocked, waiting, and time waiting are collectively referred to as blocking states. This is also possible, but here I want to link the state of the thread with the method call in Java, so the two states of waiting and time waiting are separate from.

2. Context switching

 For a single-core CPU (for a multi-core CPU, this is understood as one core), the CPU can only run one thread at a time. Switching to running another thread while running one thread is called thread context switching (the same is true for processes).
 

Three.Methods in the Thread class

By looking at the source code of the java.lang.Thread class we can see:
 

The Thread class implements the Runnable interface. In the Thread class, there are some key attributes. For example, name is the name of the Thread, which can be specified through the parameters in the constructor of the Thread class. Thread name, priority indicates the priority of the thread (the maximum value is 10, the minimum value is 1, the default value is 5), daemon indicates whether the thread is a daemon thread, and target indicates the task to be executed.
 The following are commonly used methods in the Thread class:
The following are several methods related to the running status of the thread:
1) start method
Start() is used to start a thread. When the start method is called, the system will start a new thread to perform user-defined subtasks. In this process, the required resources will be allocated to the corresponding thread. .
 2) run method
The run() method does not need to be called by the user. After starting a thread through the start method, when the thread obtains the CPU execution time, it enters the run method body. to perform specific tasks. Note that if you inherit the Thread class, you must override the run method and define the specific tasks to be performed in the run method.
 3) sleep method
The sleep method has two overloaded versions:
Sleep is equivalent to letting the thread sleep, handing over the CPU, and letting the CPU perform other tasks.
But one thing to note is that the sleep method will not release the lock. That is to say, if the current thread holds a lock on an object, other threads will not be able to access the object even if the sleep method is called. It will be clear when you look at the following example:
1
2
3
##sleep(long millis) //The parameter is milliseconds
sleep(long millis,int nanoseconds) //The first parameter is milliseconds, the second parameter is nanoseconds
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class Test {
                                                                                                                                                                               
# private Object object = new Object();
public static void main(String[] args) throws IOException {
Test test = new Test();
MyThread thread1 = test.new MyThread();
MyThread thread2 = test.new MyThread();
thread1.start();
                                             thread2.start();                                                                    
# public void run() {
synchronized (object) {
i++;
System.out.println("i:"+i);
try ).sleep(10000);
                                                                   System.out.println ("Thread"+Thread.currentThread().getName()+"Sleep End");
        i++;
               System.out.println("i:"+i);
                                  
##                                                                            
Output result:

As can be seen from the above output result, when Thread-0 enters the sleep state, Thread-1 Didn't perform specific tasks. Only when Thread-0 completes execution, and Thread-0 releases the object lock, does Thread-1 begin execution.
Note that if the sleep method is called, the InterruptedException must be caught or thrown to the upper layer. When the thread sleep time is up, it may not be executed immediately because the CPU may be performing other tasks at this time. So calling the sleep method is equivalent to putting the thread into a blocking state.
 4) yield method
Calling the yield method will cause the current thread to hand over CPU permissions and let the CPU execute other threads. It is similar to the sleep method and does not release the lock. However, yield cannot control the specific time to hand over the CPU. In addition, the yield method can only allow threads with the same priority to have the opportunity to obtain CPU execution time.
Note that calling the yield method does not put the thread into the blocking state, but returns the thread to the ready state. It only needs to wait to reacquire the CPU execution time, which is different from the sleep method.
5) join method
The join method has three overloaded versions:
1
2
3
join()
join(long millis) // The parameter is milliseconds
join(long millis,int nanoseconds) //The first parameter is milliseconds, the second parameter is nanoseconds
If the thread.join method is called in the main thread, the main method will wait for the thread thread to complete execution or wait for a certain period of time. If the join method without parameters is called, wait for the thread to complete execution. If the join method with a specified time parameter is called, wait for a certain event.
Look at the following example:
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
public class Test {
                                                                                                                                                                                                                                                                                      ("Enter the thread"+Thread.currentThread().getName());
Test test = new Test();
MyThread thread1 = test.new MyThread();
       thread1.start();
                                                                                                                                                                                                                                                                                 because through
# thread1.join ();
System.out.println ("thread"+thread.currentthRead (). Getname ()+"continues to execute");
##} Catch (InterruptedException e) {
                                                                                                                                            TODO Auto-generated catch block
              e.printStackTrace(); #    
       class MyThread extends Thread{
                                                                                                                                                                                                                                                                           .currentThread ().getName());
# // Todo: Handle Exception
}
System.out.println ("thread"+thread.currentthread (). GetName ()+");
}
}
}
Output result:

It can be seen that when the thread1.join() method is called, the main thread will enter the waiting state. Then wait for thread1 to finish executing before continuing.
Actually calling the join method calls the wait method of Object. This can be known by viewing the source code:
 

Wait method This will cause the thread to enter a blocked state, release the lock held by the thread, and hand over CPU execution permissions.
Since the wait method will cause the thread to release the object lock, the join method will also cause the thread to release the lock held on an object. The specific use of wait method is given in the following article.
6) interrupt method
Interrupt, as the name suggests, means interruption. Calling the interrupt method alone can cause the thread in the blocked state to throw an exception, that is, it can be used to interrupt a thread in the blocked state; in addition, the interrupt method and isInterrupted() method are used to stop the running thread.
Let’s look at an example:
##public class Test {
##1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Public Static Void Main (String [] ARGS) Throws IOEXCEPTION {
Test Test = New Test ();
# mythread thread = test. new MyThread();
thread.start();
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
                                                                                                                                                      Mythread extends thread {
# @Override
Public void run () {
## Try {
## System.out.println ("Enter Sleep Status") ;
                                                                                                                                                                                                                                               
## System.out.println ("Get the Interrupted Abnormal");
##}
System.out.println ("Run method is executed");
}
}
}
Output result:

It can be seen from here that the thread in the blocked state can be interrupted through the interrupt method. So can a thread in a non-blocking state be interrupted? Look at the following example:
#1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test {
           
      public static void main(String[] args) throws IOException  {
Test test = new Test();
MyThread thread = test.new MyThread();
thread.start();
try {
                                                                                                                                  to  ();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(i System.out.println(i+" while loop");
i++;
}
}
}
}
When you run this program, you will find that the while loop will continue to run until the value of variable i exceeds Integer.MAX_VALUE. Therefore, calling the interrupt method directly cannot interrupt the running thread.
But if the running thread can be interrupted with isInterrupted(), because calling the interrupt method is equivalent to setting the interrupt flag to true, then you can interrupt the thread by calling isInterrupted() to determine whether the interrupt flag is set. implement. For example, the following code:
6
#1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Test {
             
##         public static void main(String[] args) throws IOException  {
Test test = new Test();
MyThread thread = test.new MyThread();
thread.start();
try {
                                                                                                              out. interrupt();
}
class MyThread extends Thread{
@Override
public void run() {
int i = 0;
while(!isInterrupted() && i
System.out.println(i+" while loop");
                                                                                                                                                                         
## When you run it, you will find that after printing several values, the while loop stops printing.
However, it is generally not recommended to interrupt the thread in this way. Generally, an attribute isStop is added to the MyThread class to mark whether to end the while loop, and then the value of isStop is determined in the while loop.
##1
2
3
4
5
7
8
9
10111213
14
class MyThread extends Thread{
private volatile boolean isStop = false;
                                                                                                                                     ’ ’ ’ ‐ to Boolean boolean ’ s ‐ ‐ ‐ ‐ ‐                                                                                                      
#         i++;
                                                                                                                                                                                                                      through stop;
}
}
Then you can terminate the while loop by calling the setStop method outside.
 7) Stop method
The stop method is an obsolete method and it is an unsafe method. Because calling the stop method will directly terminate the call of the run method and throw a ThreadDeath error. If the thread holds an object lock, the lock will be completely released, resulting in inconsistent object status. Therefore, the stop method will basically not be used.
8) destroy method
The destroy method is also an obsolete method. Basically not used.
The following are several methods related to thread properties:
1) getId
Used to get the thread ID
2) getName and setName
Used to get or set the thread name.
3) getPriority and setPriority
Used to get and set thread priority.
4) setDaemon and isDaemon
Used to set whether a thread becomes a daemon thread and determine whether a thread is a daemon thread.
The difference between daemon threads and user threads is that the daemon thread depends on the thread that created it, while the user thread does not. To give a simple example: if a daemon thread is created in the main thread, when the main method finishes running, the daemon thread will also die. The user thread will not. The user thread will continue to run until it is completed. In the JVM, a garbage collector thread is a daemon thread.
The Thread class has a commonly used static method currentThread() to obtain the current thread.
Most of the methods in the Thread class have been mentioned above, so how will the method calls in the Thread class cause changes in the thread state? The following picture is an improvement on the above picture:

The above is the detailed content of Java concurrent programming: How to use the Thread class?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Four ways to parse XMLNext article:Four ways to parse XML

Related articles

See more