Java concurrency Programming: Using the thread class The following is the directory outline of this article: I. Thread status two. Context switch three. Methods in the Thread class reprinted from: http://www.cnblogs.com/dolphin0520/p/3920357 . html one. The state of a threadthreads go through a number of States, from creation to eventual extinction. In general, threads include the following states: Create (new), Ready (runnable), run (running), block (blocked), time waiting, waiting, extinction (dead). The following diagram depicts the state of a thread from creation to extinction:
In some tutorials, blocked, waiting, and time waiting are collectively known as blocking states, which is also possible, except that I want to associate the state of the thread with the method call in Java, so the waiting and time waiting two states are separated. Two. Context Switchesfor a single-core CPU (for multicore CPUs, this is understood here as a core), the CPU can only run one thread at a time, and when the process of running one thread goes to run another thread, this is called a thread-context switch (similar to a process). Three. Methods in the thread class by looking at the source code of the Java.lang.Thread class:
The thread class implements the Runnable interface, in the thread class, some of the more critical properties, such as name is the name of the thread, and the thread name can be specified by the parameters in the constructor of the thread class. Priority indicates the thread's precedence (maximum value is 10, minimum value is 1, default is 5), daemon indicates whether the thread is a daemon thread, and target represents the task to perform.The following are common methods in the thread class:Here are a few methods that relate to the thread's running state: 1) Start method Start () starts a thread, and when the Start method is called, the system opens a new thread to execute the user-defined subtask, in which the appropriate thread is assigned the required resources. 2) The Run Method run () method does not require the user to call, when starting a thread through the Start method, when the thread obtains the CPU execution time, then enters the Run method body to carry on the concrete task. Note that inheriting the thread class must override the Run method and define the specific task to be performed in the Run method. 3) The Sleep method has two overloaded versions of the Sleep method:
123 |
Sleep (long Millis)//parameter is milliseconds sleep (long millis,int nanoseconds)///First parameter is millisecond, second parameter is nanosecond |
Sleep is the equivalent of having a thread sleeping, handing over the CPU, and allowing the CPU to perform other tasks. However, it is important to note that the sleep method does not release the lock, which means that if the current thread holds a lock on an object, other threads cannot access the object even if the sleep method is called. See the following example to make it clear:
123456789101112131415161718192021222324252627282930313233 |
public class Test { private int i = 10; 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 (); } class MyThread extends thread{ @Override public void Run () { synchronized (Object) { i++; System.out.println ("I:" +i); try {       SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "Go to Sleep"); thread.currentthread (). Sleep (10000); } catch (Interruptedexception e) { //Todo:handle exception }       SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "End of Sleep"); i++; system.out.println ("I:" +i) ; } } }} |
Output Result:
As can be seen from the above results, when Thread-0 goes to sleep, Thread-1 does not perform specific tasks. Thread-1 only begins execution when the object lock is Thread-0 released when Thread-0 is finished executing. Note that if you call the Sleep method, you must either catch the Interruptedexception exception or throw the exception to the upper layer. When a thread sleeps at full time, it does not necessarily get executed immediately, because the CPU may be performing other tasks at this time. So calling the sleep method is equivalent to getting the thread into a blocking state. 4) The yield method calls the yield method to let the current thread hand over the CPU permissions, allowing the CPU to execute other threads. It is similar to the sleep method and does not release the lock. However, yield does not control the specific time to hand over the CPU, and the yield method only allows threads with the same priority to have the opportunity to get CPU execution time. Note that calling the yield method does not cause the thread to go into a blocking state, but instead allows the thread to return to the ready state, which only needs to wait for the CPU execution time to be fetched again, which is not the same as the sleep method. 5) The Join method has three overloaded versions of the Join method:
123 |
Join () Join (long Millis)//parameter is millisecond join (long millis,int nanoseconds)///First parameter is millisecond, second parameter is nanosecond |
If the Thread.Join method is called in the main thread, the main method waits for the thread thread to complete or wait for a certain amount of time. If the call is a parameterless join method, wait for the thread to finish executing and wait for a certain event if the join method that specified the time parameter is called. Take a look at the following example:
123456789101112131415161718192021222324252627282930 |
public class Test { public static void main (string[] args) throws ioexception { system.out.println ("Enter thread" + Thread.CurrentThread (). GetName ()) test test = new test (); mythread thread1 = test.new MyThread (); thread1.start (); try {         SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "Wait") ; thread1.join ();          SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "continue execution"); } catch (Interruptedexception e) { //TODO auto-generated Catch block e.printstacktrace (); } } class MyThread extends Thread{ @Override public void Run () { system.out.println (" Enter Thread "+thread.currentthread (). GetName ()); try { Thread.CurrentThread (). Sleep (n); } catch (interruptedexception e) { //todo:hAndle exception }          SYSTEM.OUT.PRINTLN ("Thread" +thread.currentthread (). GetName () + "execution complete"); } }} |
Output Result:
As you can see, when the Thread1.join () method is called, the main thread enters the wait and waits for the thread1 to execute before continuing. Actually calling the join method is called the wait method of object, which can be learned by viewing the source:
The wait method causes the thread to go into a blocking state, releasing the lock that the thread occupies and handing over the CPU execution permissions. Because the wait method causes the thread to release the object lock, the Join method also causes the thread to release locks held on an object. The specific wait method is used in the following article. 6) Interrupt method interrupt, as the name implies, that is the meaning of interruption. Calling the interrupt method alone can cause a blocked thread to throw an exception, which can be used to break a thread that is in a blocking state, and to stop a running thread by using the interrupt method and the Isinterrupted () method. Let's look at an example:
12345678910111213141516171819202122232425262728 |
public class Test { public static void main (string[] args) throws ioexception { test test = new test (); mythread thread = test.new MyThread (); Thread.Start (); try { thread.currentthread (). Sleep (+); } catch (Interruptedexception e) { } Thread.Interrupt (); } class MyThread extends thread{ @Override & NBsp; public void Run () { try { System.out.println ("Go to Sleep"); thread.currentthread (). Sleep (10000); system.out.println ("Sleep Complete"); } catch (Interruptedexception e) {          SYSTEM.OUT.PRINTLN ("Get Interrupt exception"); } system.out.println ("Run Method Execution complete"); } }} |
Output Result:
As you can see from here, you can break a blocked thread by using the interrupt method. Can you break a non-blocking thread? Look at the following example:
12345678910111213141516171819202122232425 |
public class Test { public static void main (string[] args) throws ioexception { test test = new test (); mythread thread = test.new MyThread (); Thread.Start (); try { thread.currentthread (). Sleep (+); } catch (Interruptedexception e) { } Thread.Interrupt (); } class MyThread extends thread{ @Override & NBsp; public void Run () { int i = 0; while (I<Integer.MAX_VALUE) { system.out.println (i + "while loop"); i+ +; } } }} |
Running the program will find that the while loop runs until the value of the variable I exceeds integer.max_value. Therefore, calling the interrupt method directly does not interrupt a running thread. However, if the Mate isinterrupted () is able to break the running thread, because calling the interrupt method is equivalent to having the interrupt flag position true, you can call isinterrupted () to determine whether the interrupt flag is set to execute in the thread break. For example, the following code:
12345678910111213141516171819202122232425 |
public class Test { public static void main (string[] args) throws ioexception { test test = new test (); mythread thread = test.new MyThread (); Thread.Start (); try { thread.currentthread (). Sleep (+); } catch (Interruptedexception e) { } Thread.Interrupt (); } class MyThread extends thread{ @Override & NBsp; public void Run () { int i = 0; while (!isInterrupted () && i< Integer.max_value) { system.out.println (i+ "while loop"); i++; } } }} |
Running will find that after printing several values, the while loop stops printing. In general, however, it is not recommended to break threads in this way, typically adding an attribute isstop in the Mythread class to flag whether to end the while loop and then to determine the value of isstop in the while loop.
1234567891011121314 |
class MyThread extends thread{ private volatile Boolean isstop = false; @Override public void Run () { int i = 0; while (!isStop ) { i++; } } public void Setstop (Boolean stop) { This.isstop = stop; } } |
You can then terminate the while loop outside by calling the Setstop method. 7) The Stop method stop method is already an obsolete method, and it is an unsafe method. Because calling the Stop method terminates the call to the Run method directly and throws a Threaddeath error, if the thread holds an object lock, the lock is completely released, causing the object state to be inconsistent. So the Stop method is basically not going to be used. 8) Destroy method Destroy method is also an obsolete method. Basic will not be used. The following are several methods that relate to thread properties: 1) getId is used to get thread ID 2) GetName and setname are used to get or set the thread name. 3) GetPriority and setpriority are used to get and set thread priority. 4) Setdaemon and Isdaemon are used to set whether the thread becomes the daemon thread and whether the thread is the daemon thread. The difference between a daemon thread and a user thread is that the daemon relies on the thread that created it, and the user thread does not depend on it. As a simple example: if you create a daemon thread in the main thread, when the main method finishes running, the daemon thread will die as well. The user thread does not, and the user thread runs until it finishes running. In the JVM, a garbage collector thread is the daemon thread. The thread class has a more commonly used static method, CurrentThread (), to get the current thread. The most of the methods in the thread class have been mentioned above, so how does a method call in the thread class cause the thread state to change? The following picture is an improvement on the above diagram:
Java Concurrency Programming: the use of the thread class