继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

如何保证Thread-1、2、3的顺序执行

我有一双明亮的眼睛
关注TA
已关注
手记 13
粉丝 19
获赞 269

/
有三个线程T1 T2 T3,如何保证他们按顺序执行-转载
在T2的run中,调用t1.join,让t1执行完成后再让T2执行
在T2的run中,调用t2.join,让t2执行完成后再让T3执行
/

方法一:

public class Test {
    private int count=2;

    public static void main(String[] args) {
        try {
            new Test().preserveOrderViaJoin();
        }catch (Exception e){
            System.out.println("error!");
        }
    }

    private void preserveOrderViaJoin() throws InterruptedException {
        Thread tmp;
        System.out.println("start!");
        for (int i=0;i<count;i++){
            tmp=new Thread(new Runnable() {
                public void run() {
                    System.out.println("Thread.currentThread().getName():"+Thread.currentThread().getName());
                }
            },"Thread"+i);
            tmp.start();
            tmp.join();
        }
        System.out.println("end!");
    }

}

方法二:

public void testCountDownLatch(){
        final CountDownLatch countDownLatch = new CountDownLatch(0);
        final CountDownLatch countDownLatch1 = new CountDownLatch(1);
        final CountDownLatch countDownLatch2 = new CountDownLatch(1);

        Thread thread1 = new Thread(new Runnable() {
            public void run() {
                try {
                    countDownLatch.await();
                    System.out.println(Thread.currentThread().getName()+"start");
                    System.out.println(Thread.currentThread().getName()+"end");
                    countDownLatch1.countDown();
                } catch (Exception e){
                    System.out.println(Thread.currentThread().getName()+"exception!");
                }
            }
        },"Thread-1");

        Thread thread2 = new Thread(new Runnable() {
            public void run() {
                try {
                    countDownLatch1.await();
                    System.out.println(Thread.currentThread().getName()+"start");
                    System.out.println(Thread.currentThread().getName()+"end");
                    countDownLatch2.countDown();
                } catch (Exception e){
                    System.out.println(Thread.currentThread().getName()+"exception!");
                }
            }
        },"Thread-2");

        Thread thread3 = new Thread(new Runnable() {
            public void run() {
                try {
                    countDownLatch2.await();
                    System.out.println(Thread.currentThread().getName()+"start");
                    System.out.println(Thread.currentThread().getName()+"end");
                } catch (Exception e){
                    System.out.println(Thread.currentThread().getName()+"exception!");
                }
            }
        },"Thread-3");

        thread1.start();
        thread2.start();
        thread3.start();
    }

根据网络上相应内容做出的整合

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP