The state of the thread
- NEW: When a thread is created, it will only be in this state for a short time. It has already allocated the necessary system resources to complete the initialization. The thread scheduler will then turn this thread into a running or blocking state;
- Ready (Runnable): In this state, as long as the scheduler allocates time slices to the thread, the thread can run;
- Blocking (Blocked): A condition that prevents a thread from running, the scheduler ignores the blocking state of the thread, does not allocate a time slice to it until the thread is in a ready state, it is possible to execute;
- Death (Dead): A thread that is in a dead or terminated state will no longer be scheduled and will not be assigned to a time slice. The way the task dies is usually returned from the Run method, or is interrupted;
Here are a few possible reasons why a thread has entered a blocking state:
- By calling Sleep (mils), the task enters the sleep state at the specified time;
- Calling wait causes the thread to hang until the thread gets notify or notifyall information, and the thread is in the ready state;
- The task waits for input and output to complete;
- The task attempts to invoke its synchronization method on an object, but the object lock is not available;
Because a thread in the blocking state is suspended and is not executed, that is, the code has a certain point in the judging state value exits and does not reach that point, in which case the task should be forced to jump out of blocking state.
Interrupt
The thread class contains the interrupt method, which is used to terminate a blocked task. Calling the interrupt method sets the interrupt state of the thread, and if a thread has been blocked or attempts to perform a blocking operation, setting the interrupt state of the thread throws a Interruptedexception exception. When the interruptedexception exception is thrown or the task calls thread.interrupted (), the thread break state is reset. This interrupt is blocked by the thread that requires us to hold the thread object.
Java SE5 is recommended to use executor to create concurrent tasks, and when the executor is raised with Shutdownnow (), it will take place a interrupt to all the threads it started. If you just want to close a particular task, not all of it, submit the task via submit, return the Future<?> object, call Cancel on the future object to break the thread, or pass True to cancel. Then the future object will have permission to invoke interrupt on that thread to terminate the thread.
Below is a look at the different blocking conditions of the thread break:
//define sleep into a blocked task
Public classSleepblockedImplementsrunnable{ Public voidrun () {Try{TimeUnit.SECONDS.sleep (10); }Catch(interruptedexception e) {System.out.println ("Interrupt from Sleep ..."); } System.out.println ("Exiting from Sleepblocked run"); }}//definition because IO goes into a blocking task Public classIoblockedImplementsRunnable {InputStream input; Publicioblocked (InputStream input) { This. Input =input; } Public voidrun () {Try{System.out.println ("Waiting for input ..."); Input.read (); }Catch(IOException e) {System.out.println ("IOException ..."); if(thread.interrupted ()) {System.out.println ("Interrupt from ioblocked ..."); }Else { Throw Newruntimeexception (); }} System.out.println ("Exiting from ioblocked ..."); }}//defined because an attempt to get an object lock into a blocked task Public classSynchronizedblockedImplementsrunnable{ Public synchronized voidf () { while(true) Thread.yield (); } Publicsynchronizedblocked () {NewThread () { Public voidrun () {f (); }}.start (); } Public voidrun () {System.out.println ("Trying to call F () ..."); f (); System.out.println ("Exiting from synchronizedblocked ...."); }}
The test classes are as follows:
Public classInterruptedtest {Private StaticExecutorservice executor =Executors.newcachedthreadpool (); Static voidTest (Runnable Task)throwsinterruptedexception{//Use the Executor submission method to submit a task, or a reference to the thread, so that the interrupt thread
Future=Executor.submit (Task); TimeUnit.SECONDS.sleep (1); System.out.println ("Interruptting" +Task.getclass (). GetName ());
By passing true to the future object's Cancel method, the interrupt is run by the blocked thread Future.cancel (true); System.out.println ("Interrupt Send to" +Task.getclass (). GetName ()); } Public Static voidMain (string[] args)throwsexception{Test (Newsleepblocked ()); Test (Newioblocked (system.in)); Test (Newsynchronizedblocked ()); }}
Output:
Interruptting com.thread.test.SleepBlocked
Interrupt Send to Com.thread.test.SleepBlocked
Interrupt from sleep ...//interrupted by a sleep-blocking thread
Exiting from Sleepblocked run
Threads that are blocked because of Io are not interrupted
Waiting for input ...
Interruptting com.thread.test.IOBlocked
Interrupt Send to Com.thread.test.IOBlocked
The thread that was blocked because the object lock was acquired was not interrupted
Trying to call F () ...
Interruptting com.thread.test.SynchronizedBlocked
Interrupt Send to Com.thread.test.SynchronizedBlocked
Exiting from ioblocked ...
As you can see from the output, You can interrupt the call to sleep, but you cannot interrupt a thread that attempts to acquire an object lock (synchronized implementation) or perform an IO task.
implementing a blocking interrupt that attempts to acquire an object lock
As can be seen from the above, synchronization object locks implemented with the Synchronized keyword cannot be interrupted when blocking. Here is an implementation that provides both a lock function and an interrupt when blocking, which is to use Reentrantlock.
Public classblockedmutex{PrivateLock lock =NewReentrantlock (); Public voidf () {Try{
Always holds the lock unless interrupted lock.lockinterruptibly (); }Catch(interruptedexception e) {System.out.println (Thread.CurrentThread (). GetName ()+ "interrupted from lock acquisition in F ()"); } }} Public classLockblockedImplementsRunnable {PrivateBlockedmutex Blockedmutex; Publiclockblocked (Blockedmutex blockedmutex) { This. Blockedmutex =Blockedmutex; } Public voidrun () {System.out.println (Thread.CurrentThread (). GetName ( )+ "Waiting for Blockedmutex ..."); BLOCKEDMUTEX.F (); System.out.println (Thread.CurrentThread (). GetName ()+ "broken out of blocked"); }} Public classInterruptedtest { Public Static voidMain (string[] args)throwsexception{Blockedmutex Blockedmutex =NewBlockedmutex (); Thread T1=NewThread (Newlockblocked (Blockedmutex)); Thread T2=NewThread (Newlockblocked (Blockedmutex)); T1.start (); T2.start (); T2.interrupt (); }}
Output:
Thread-0 waiting for Blockedmutex ....
Thread-1 waiting for Blockedmutex ....
Thread-0 broken out of blocked call
Thread-1 interrupted from lock acquisition in F ()
Thread-1 broken out of blocked call
Both tasks are the F method that uses the same Blockedmutex instance, and the F method acquires the object lock in a permanent possession lock so that only the task that is executed first can hold the lock, and then the task waits. The test saw T1 possession lock, T2 waiting for the lock, interrupt T2, see T2 driven task inside throw interruptedexception, which also shows that the Reentrantlock lock can be interrupted under blocking .
Blocking interrupts for IO operations
Check for interrupts
From the above study, the thread will throw an exception (IO blocking or synchronized blocking exception, cannot be interrupted) when the thread enters the block or when it is going into blocking, and the interrupt of the call is called. In the task, it is not always possible to cause the thread to enter blocking code, when the task execution does not lead to blocking the code, you can call the thread's interrupted method to check the interrupt state, because the thread's interrupt method sets the interrupt flag bit, The interrupted method is able to read the flag bit and reset the flag bit. Take a look at the following example:
Public classInterruptedcheckImplementsRunnable {Private DoubleD =1d; Public voidrun () {Try { while(!thread.interrupted ()) {System.out.println ("Sleeping ...");
//thread sleep 2s, enter blocking, if interrupt in sleep time, will throw an exception Thread.Sleep (2000); System.out.println ("Calculating ...");
//Here to calculate the task, there will be a certain time, but the thread will not enter the blocking state. If interrupt is performed during the operation, no exception is thrown and the interrupt flag bit is set for(inti=1;i<25000000;i++) {D= D + (Math.PI + MATH.E)/D; }} System.out.println ("Detected interrupted, not from blocked ..."); }Catch(interruptedexception e) {System.out.println ("Interrupted from blocked ..."); } }} Public Static voidMain (string[] args)throwsexception{Thread Thread=NewThread (NewInterruptedcheck ()); Thread.Start ();
//Here man's sleep time is a different value, it can be in a different state of thread (sleep into blocking or normal execution operation) Interrupt TimeUnit.MILLISECONDS.sleep (2100); System.out.println ("Interruptting ..."); Thread.Interrupt (); } output: Main's sleep time is 1500milsec sleeping...interruptting...interrupted from blocked ...
When the sleep time of main is 2100milsec
Detected interrupted, not from blocked ...
As you can see, in a blocked state that can be interrupted, the thread will exit the task in the form of throwing an exception. In the running state, the interrupt flag bit of the interrupted thread is set, and the interrupted method can read to the thread that flag bit to determine if the thread is interrupted and then execute the policy judgment of the exit task.
The state of the thread of Java multithreaded Learning and the process of threading