The interview encountered such a problem: threads A and thread B, how to control thread B in line a start 3 seconds or after thread a runs to start?
The topic shows that thread B's start-up time is to meet two conditions:
1. After thread a starts 3 seconds
2. After the end of thread a runs
This means that as long as the above two conditions have a satisfying, thread B will start.
Use Countdownlatch to control call timing, the code is as follows:
1 Public classRunAImplementsRunnable {2 PrivateCountdownlatch CDL;3 PublicRunA (Countdownlatch CDL) {4 This. CDL =CDL;5 }6 @Override7 Public voidrun () {8 //TODO auto-generated Method Stub9 Try {TenThread.Sleep (1000); One Cdl.countdown (); ASystem.out.println ("A run Over"); -}Catch(interruptedexception e) { - //TODO auto-generated Catch block the e.printstacktrace (); - } - } -}
1 Public classRunbImplementsRunnable {2 PrivateCountdownlatch CDL;3 PublicRunb (Countdownlatch CDL) {4 This. CDL =CDL;5 }6 @Override7 Public voidrun () {8 //TODO auto-generated Method Stub9 Try {TenCdl.await (3000, timeunit.milliseconds); OneSystem.out.println ("B run Over"); A}Catch(interruptedexception e) { - //TODO auto-generated Catch block - e.printstacktrace (); the } - } -}
1 Public classTest {2 Public Static voidMain (string[] args) {3Countdownlatch CDL =NewCountdownlatch (1);4Thread TA =NewThread (NewRunA (CDL));5Thread TB =NewThread (NewRunb (CDL));6 Ta.start ();7 Tb.start ();8 }9}
Control the boot order of two threads