The state of the thread
Threads 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).
When a new thread is needed to execute a subtask, a thread is created. However, after a thread is created, it is not immediately ready because the thread is running with some conditions (such as memory resources, a blog post in the previous JVM memory area that knows the program counter, the Java stack, and the local method stack are thread-private, so you need to allocate a certain amount of memory space to the thread). Only if all the conditions required for the thread to run are met, the ready state is entered. When a thread is in a ready state, it does not mean that the CPU execution time is immediately available, and perhaps the CPU is doing something else at this time, so it waits. When the CPU execution time is obtained, the thread actually goes into the running state.
While the thread is running, there may be several reasons why the current thread does not continue to run, such as when the user proactively causes the thread to sleep (after a certain amount of sleep), the user actively lets the thread wait, or is blocked by the synchronization block, which corresponds to multiple states: time Waiting (sleep or wait for a certain event), waiting (waiting to be awakened), blocked (blocking).
When a sudden interruption or completion of a sub-task, the thread will be extinct.
Thread class
Publicclass Thread implements Runnable {/* Make sure registernatives are the first thing <clinit> does. */pri vate static native void Registernatives (); static {registernatives (); } private volatile char name[]; private int priority; Private Thread THREADQ; Private long eetop; /* Whether or not to single_step the this thread. */Private Boolean single_step; /* Whether or not, the thread is a daemon thread. */Private Boolean daemon = false; /* JVM state */Private Boolean stillborn = false; /* What'll be run. */private Runnable target; /* The group of this thread */private threadgroup Group; /* The context ClassLoader for this thread */private ClassLoader contextclassloader; /* The inherited accesscontrolcontext of this thread */private AccessControlContext inheritedaccesscontrolcontext; /* for autonumbering anonymous threads. */private static int Threadinitnumber; private static synchronized int nextthreadnum () {return threadinitnumber++; }/* ThreadLocal values pertaining to this thread. This map was maintained * by the ThreadLocal class. */Threadlocal.threadlocalmap threadlocals = null; /* * Inheritablethreadlocal values pertaining to this thread. This map was * maintained by the Inheritablethreadlocal class. */Threadlocal.threadlocalmap inheritablethreadlocals = null;
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.
Here are a few ways to relate to the running state of a thread:
1) Start method
Start () is used to start 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) Run method
The run () method does not require a user to invoke, and when a thread is started by the Start method, when the thread obtains the CPU execution time, it enters the Run method body to perform the specific 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) Sleep method
There are two overloaded versions of the Sleep method:
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 lock even if the sleep method is called.
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) Yield method. yield, like sleep (), can be called directly with the thread class, and invoking the yield method will let the current thread hand over the CPU permissions and allow 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. if no thread of the same level is waiting for the CPU to execute, the thread continues execution.
5) Thejoin method is called with the thread object, and if another thread B's Join method is called in a thread A, thread a waits for thread B to execute before executing.
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 you are calling the parameterless join method, wait for the thread to finish executing, and if you are calling a join method that specifies a time parameter, wait a certain amount of time.
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 (5000); } catch (Interruptedexception e) {//Todo:handle exception} System.out.println ("Thread "+thread.currentthread (). GetName () +" execution complete "); } }} Results:
Enter Thread main
Thread Main waits
Enter Thread Thread-0
Thread Thread-0 Execution Complete
Thread main continues execution
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 the wait method that called the object (view 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, 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.
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 public void Run () { try { System.out.println (" Go to Sleep State "); 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");}}}
Results:
Go to sleep State
Get interrupted
The Run method finishes executing
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:
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 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:
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 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.
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) Stop method
The 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
The Destroy method is also an obsolete method. Basic will not be used.
Here are a few ways to relate to thread properties:
1) GetID used to get thread ID
2) GetName and setname 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.
Thread of Java concurrency