Control the startup sequence of two threads.
In the interview, I encountered the following question: How can I control thread B to start after thread A starts for 3 seconds or after thread A finishes running?
The question shows that thread B's start time must meet two conditions:
1. 3 seconds after thread A starts
2. After thread A finishes running
That is to say, as long as one of the above two conditions is met, thread B will start.
Use CountDownLatch to control the call sequence. The Code is as follows:
1 public class RunA implements Runnable { 2 private CountDownLatch cdl; 3 public RunA(CountDownLatch cdl){ 4 this.cdl = cdl; 5 } 6 @Override 7 public void run() { 8 // TODO Auto-generated method stub 9 try {10 Thread.sleep(1000);11 cdl.countDown();12 System.out.println("A run over");13 } catch (InterruptedException e) {14 // TODO Auto-generated catch block15 e.printStackTrace();16 }17 }18 }
1 public class RunB implements Runnable { 2 private CountDownLatch cdl; 3 public RunB(CountDownLatch cdl){ 4 this.cdl = cdl; 5 } 6 @Override 7 public void run() { 8 // TODO Auto-generated method stub 9 try {10 cdl.await(3000, TimeUnit.MILLISECONDS);11 System.out.println("B run over");12 } catch (InterruptedException e) {13 // TODO Auto-generated catch block14 e.printStackTrace();15 }16 }17 }
1 public class Test {2 public static void main(String[] args) {3 CountDownLatch cdl = new CountDownLatch(1);4 Thread ta = new Thread(new RunA(cdl));5 Thread tb = new Thread(new RunB(cdl));6 ta.start();7 tb.start();8 }9 }