Assuming that thread 1/thread 2/thread 3, threads 3 must start executing after the line 1/thread 2 execution completes, There are two ways to implement
- Join method for the thread class: causes the host thread to block the specified time or until the parasitic threads have finished executing
- Countdownlatch class: Specifies a counter that cancels blocking when the counter is zeroed
Importjava.util.concurrent.CountDownLatch;Importorg.junit.Assert;Importorg.junit.Test;/*** @Description: How to specify thread order*/ public classThreadordertest {Private LongMillisunit = 1000; Private intCount = 2; classThreadorder {/*** Join method enables multiple threads to execute sequentially * *@return * @throwsinterruptedexception*/ public LongPreserveorderviajoin ()throwsinterruptedexception {LongStartmillis =System.currenttimemillis (); Thread tmp; for(inti = 0; I < count; i++) {tmp=NewThread (NewRunnable () {@Override public voidRun () {Try{thread.sleep (millisunit); } Catch(interruptedexception E) {e.printstacktrace (); } } }, "join-" +i); Tmp.start (); Tmp.join ();//continuously detects if the thread is complete and the execution is complete before continuing. } returnSystem.currenttimemillis ()-startmillis; } /*** Contdownlatch can block multiple threads at the same time, but they can execute concurrently * *@return * @throwsinterruptedexception*/ public LongPreserveorderviacontdownlatch ()throwsinterruptedexception {LongStartmillis =System.currenttimemillis (); FinalCountdownlatch Countdownlatch =NewCountdownlatch (count); for(inti = 0; I < count; i++) { NewThread (NewRunnable () {@Override public voidRun () {Try{thread.sleep (millisunit); } Catch(interruptedexception E) {e.printstacktrace (); } Countdownlatch.countdown ();//as long as the counter is zeroed, the waiting thread can start executing, thus achieving the concurrency effect } }, "countdownlatch-" +i). Start (); } countdownlatch.await (); returnSystem.currenttimemillis ()-startmillis; }} @Test public voidTestpreserveorderviajoin ()throwsinterruptedexception {threadorder Threadorder=NewThreadorder (); Assert.assertequals (count, threadorder.preserveorderviajoin ()/millisunit); } @Test public voidTestpreserveorderviacontdownlatch ()throwsinterruptedexception {threadorder Threadorder=NewThreadorder (); Assert.assertequals (1, Threadorder.preserveorderviacontdownlatch ()/millisunit); }}
Java multithreaded series four--controlling thread execution order