Control the startup sequence of two threads.

Source: Internet
Author: User

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 }

 

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.