Control the boot order of two threads

Source: Internet
Author: User
Tags stub

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

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.