"Java Concurrency" End Task

Source: Internet
Author: User

Thread state New State

When a thread is created, it is briefly in this state. A thread in this state has allocated the necessary system resources, is eligible for CPU time, and waits for the scheduler to turn it into a operational or blocking state;

Ready state

In this state, as long as the scheduler to allocate time slices to the thread, it can run immediately;

Blocking state

A thread is prevented from running because a condition is not satisfied, and the state is ignored by the scheduler until the condition is satisfied, to a ready state;

Death status

The state in which the thread runs or is interrupted, and the state cannot be dispatched and the CPU time is not allocated;

How threads enter a blocking state
    • Call the Sleep method
    • Call the Wait method
    • The task waits for an input and output to complete
    • Call other synchronization control methods to wait for other threads to release the lock
Break thread blocking and interrupts in threads

Look at the code first, as follows:

 Packageconcurrency;Importjava.util.concurrent.*;ImportJava.io.*;classSleepblockedImplementsRunnable { Public voidrun () {Try{TimeUnit.SECONDS.sleep (100); } Catch(interruptedexception e) {System.out.println ("Interruptedexception"); } System.out.println ("Exiting Sleepblocked.run ()"); }}classIoblockedImplementsRunnable {PrivateInputStream in;  Publicioblocked (InputStream) { in=is ; }     Public voidrun () {Try{System.out.println ("Waiting for Read ():");        In.read (); } Catch(IOException e) {if(Thread.CurrentThread (). isinterrupted ()) {System.out.println ("Interrupted from blocked I/o"); } Else {                Throw NewRuntimeException (e); }} System.out.println ("Exiting Ioblocked.run ()"); }}classSynchronizedblockedImplementsRunnable { Public synchronized voidf () { while(true)//Never releases lockThread.yield (); }     Publicsynchronizedblocked () {NewThread () { Public voidrun () {f ();//Lock acquired by this thread}}.start (); }     Public voidrun () {System.out.println ("Trying to call F ()");        f (); System.out.println ("Exiting Synchronizedblocked.run ()"); }} Public classinterrupting {Private StaticExecutorservice exec =Executors.newcachedthreadpool (); Static voidTest (Runnable R)throwsinterruptedexception { Future<?> f =Exec.submit (R); TimeUnit.MILLISECONDS.sleep (100); System.out.println ("Interrupting" +R.getclass (). GetName ()); F.cancel (true);//interrupts if runningSystem.out.println ("Interrupt sent to" +R.getclass (). GetName ()); }     Public Static voidMain (string[] args)throwsException {Test (Newsleepblocked ()); Test (Newioblocked (system.in)); Test (Newsynchronizedblocked ()); TimeUnit.SECONDS.sleep (3); System.out.println ("Aborting with System.exit (0)"); System.exit (0);//since last 2 interrupts failed    }} 
View Code

In the above code, there are three scenarios for entering the blocking state: Calling the Sleep method, waiting for Io, waiting for other threads to release the lock;

And try to invoke the future of the Cancel method to break the blocked thread, from the running results can be found that only sleep can be interrupted, other waiting for IO and waiting for lock release cannot be interrupted This can also be seen from the sleep method throws a Interruptedexception exception, the other two will not throw the exception;

What about the interrupts for the IO blocking and mutex blocking threads?

Interrupt io Blocking

Mode one, call Shutdownnow to close the thread pool and call the Close method to close the IO stream resource;

Mode two, using NiO

Interrupt Mutex Lock blocking

Use the Reentrantlock lock in the concurrency library;

PS: If it is the same thread, it is possible to invoke other synchronized methods in the same object;

Check for interrupts

Call thread.interrupted () to see if interrupt () has been called and clears the interrupt state to avoid interruption being notified two times;

"Java Concurrency" End Task

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.