Java Multi-thread four (threading operations)

Source: Internet
Author: User

This article from: Gao | Coder, the original address: http://blog.csdn.net/ghsau/article/details/17560467, reprint please specify.

Threads interrupt thread break involves three methods, as follows:

The interrupt () method is used in the interrupt thread, which is generally understood as long as a thread is started and the method is called, the thread cannot proceed, and a small example:

 
1  Public classInterrupttest {2      Public Static voidMain (string[] args)throwsinterruptedexception {3MyThread T =NewMyThread ("MyThread");4 T.start ();5Thread.Sleep (100);//Sleep 100 ms6T.interrupt ();//Interrupt T Thread7     }8 }9 classMyThreadextendsThread {Ten     inti = 0; One      PublicMyThread (String name) { A         Super(name); -     } -      Public voidrun () { the          while(true) {//dead Loop, waiting to be interrupted -System.out.println (GetName () + getId () + "performed" + ++i + "Times"); -         } -     } +}

After running, we found that the thread T has been executing, not interrupted, the original interrupt () is deceptive, Khan! in fact, the interrupt () method is not the execution of the broken thread, but a token to call the method's threading object, set its interrupt state to true, through the isinterrupted () method can get this thread state , We will make a small change to the above program:

 
1  Public classInterrupttest {2      Public Static voidMain (string[] args)throwsinterruptedexception {3MyThread T =NewMyThread ("MyThread");4 T.start ();5Thread.Sleep (100);//Sleep 100 ms6T.interrupt ();//Interrupt T Thread7     }8 }9 classMyThreadextendsThread {Ten     inti = 0; One      PublicMyThread (String name) { A         Super(name); -     } -      Public voidrun () { the          while(!isinterrupted ()) {//the current thread has not been interrupted, the execution -System.out.println (GetName () + getId () + "performed" + ++i + "Times"); -         } -     } +}

In this case, the thread is successfully interrupted and executed. When many people implement a thread class, they add a flag flag so that the control thread stops executing, which is completely unnecessary and can be implemented perfectly by the interrupt state of the thread itself. If the thread is calling the wait (), wait (long), or wait (long, int) method of the Object class, or the class's join (), join (long), join (long, int), sleep (long), or sleep (long , int) is blocked during the method, its interrupt state is cleared, and it will receive a interruptedexception. We can catch the exception and do some processing . In addition, thethread.interrupted () method is a static method that determines the interrupt state of the current thread, and it is important to note that the interrupt state of the thread is purged by the method . In other words, if the method is called twice in a row, the second call will return False (except in the case where the current thread is interrupted again until the first call has cleared its break state and the second call has finished verifying the break state).

Threading Concessions

The thread withdraws for the executing thread, and in some cases gives up the CPU resources to other threads to execute , to see a small example:

 
1  Public classYieldtest {2      Public Static voidMain (string[] args)throwsinterruptedexception {3         //To create a thread object4Yieldthread T1 =NewYieldthread ("T1");5Yieldthread t2 =NewYieldthread ("T2");6         //Start Thread7 T1.start ();8 T2.start ();9         //Main thread Hibernate 100 msTenThread.Sleep (100); One         //terminating a thread A t1.interrupt (); - t2.interrupt (); -     } the } - classYieldthreadextendsThread { -     inti = 0; -      PublicYieldthread (String name) { +         Super(name); -     } +      Public voidrun () { A          while(!isinterrupted ()) { atSystem.out.println (GetName () + "performed" + ++i + "Times"); -             if(i% 10 = = 0) {//when I can divide the 10 evenly, the concession - Thread.yield (); -             } -         } -     } in}

Output is slightly, from the output can be seen, when a thread (T1 or T2) executed to 10, 20, 30, and so on, will immediately switch to another thread execution, and then alternately executed, so back and forth. Note that if there is synchronized thread synchronization, the thread concession does not release the lock (monitor object).

Thread Sleep

thread sleep process, if it is within the synchronized thread synchronization, is to hold the lock (monitor object) , that is, the thread is closed to sleep, other threads do not come in, to see a small example:

 
1  Public classSleeptest {2      Public Static voidMain (string[] args) {3         //Create a Shared object4Service service =NewService ();5         //Creating Threads6Sleepthread T1 =NewSleepthread ("T1", service);7Sleepthread t2 =NewSleepthread ("T2", service);8         //Start Thread9 T1.start ();Ten T2.start (); One     } A      - } - classSleepthreadextendsThread { the     PrivateService service; -      PublicSleepthread (String name, service service) { -         Super(name); -          This. Service =Service; +     } -      Public voidrun () { + Service.calc (); A     } at } - classService { -      Public synchronized voidCalc () { -System.out.println (Thread.CurrentThread (). GetName () + Prepare calculation); -System.out.println (Thread.CurrentThread (). GetName () + "feel tired, start sleeping"); -         Try { inThread.Sleep (10000);//sleep for 10 seconds . -}Catch(interruptedexception e) { to             return; +         } -System.out.println (Thread.CurrentThread (). GetName () + "wake up and start counting"); theSystem.out.println (Thread.CurrentThread (). GetName () + "compute complete"); *     } $}

A thread merge thread merge takes precedence over the thread that invokes the method, and then executes the current thread, looking at a small example: 
1  Public classJointest {2      Public Static voidMain (string[] args)throwsinterruptedexception {3Jointhread T1 =NewJointhread ("T1");4Jointhread t2 =NewJointhread ("T2");5 T1.start ();6 T2.start ();7 T1.join ();8 T2.join ();9SYSTEM.OUT.PRINTLN ("The main thread starts executing!") ");Ten     } One } A classJointhreadextendsThread { -      PublicJointhread (String name) { -         Super(name); the     } -      Public voidrun () { -          for(inti = 1; I <= 10; i++) -System.out.println (GetName () + getId () + "performed" + i + "Times"); +     } -}

T1 and T2 are executed before continuing the main thread execution,The so-called merger is to wait for other threads to execute, and then execute the current thread, as if the other threads were merged into the current thread execution .。 The thread priority thread has a minimum priority of 1, the highest priority is 10, and it looks like 10 levels, but the 10 levels can not correspond to the CPU, and it is unknown that the thread class provides three constants of precedence, as follows:
java.lang.thread
public static final int Max_ Priority ten
public static final int Min_ Priority 1
public static final int NORM _priority 5
After we create the thread object, the default is 5 if the setting priority is not displayed. Priority can be regarded as a privilege, high priority, the opportunity to get CPU scheduling is big, the priority is low, the opportunity to get CPU scheduling is small, this and our real life is the same ah, the fittest. The example of thread priority is not written, it is relatively simple. Wait () and sleep () difference is too big, but in the Java thread interview question is very common problem, I believe you read this column, can easily answer, here no longer repeat.

Java Multi-thread four (threading operations)

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.