按序执行

题型:多线程

难度系数:简单

题目:有三个目标方法,用于打印出不同的结果。现提供三个线程,分别执行不同的方法,需按一定的顺序执行这三个方法。

示例:

1、

输入: [1,2,3]
输出: "onetwothree"
解释: 
有三个线程会被异步启动。
输入 [1,2,3] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 two() 方法,线程 C 将会调用 three() 方法。
正确的输出是 "onetwothree"。

2、

输入: [1,3,2]
输出: "onetwothree"
解释: 
输入 [1,3,2] 表示线程 A 将会调用 one() 方法,线程 B 将会调用 three() 方法,线程 C 将会调用 two() 方法。
正确的输出是 "onetwothree"。

无论方法如何分配执行,结果都是onetwothree

解决此类问题有多种方式,主要涉及内容为多线程间的通信。利用信号量或者CountDownLatch、CyclicBarrier等都可以

这里主要介绍信号量和CountDownLatch

1、利用Semaphore

需要注意的是semaphore的permit得设为0,并且在第一个需要执行的方法中添加release()。

class Foo {

    public Semaphore seam_two = new Semaphore(0);

    public Semaphore seam_three = new Semaphore(0);



    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        seam_two.release();
        
    }

    public void second(Runnable printSecond) throws InterruptedException {
        
        seam_two.acquire();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        seam_three.release();
        
    }

    public void third(Runnable printThird) throws InterruptedException {
        
        seam_three.acquire();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
        
    }
}

 

2、利用CountDownLatch

class Foo {

    //public Semaphore seam_two = new Semaphore(0);

    //public Semaphore seam_three = new Semaphore(0);

    public CountDownLatch countDownLatch1 = new CountDownLatch(1);
    public CountDownLatch countDownLatch2 = new CountDownLatch(1);


    public Foo() {
        
    }

    public void first(Runnable printFirst) throws InterruptedException {
        
        // printFirst.run() outputs "first". Do not change or remove this line.
        printFirst.run();
        //seam_two.release();
        countDownLatch1.countDown();
    }

    public void second(Runnable printSecond) throws InterruptedException {
        countDownLatch1.await();
        //seam_two.acquire();
        // printSecond.run() outputs "second". Do not change or remove this line.
        printSecond.run();
        //seam_three.release();
        countDownLatch2.countDown();
    }

    public void third(Runnable printThird) throws InterruptedException {
        countDownLatch2.await();
        //seam_three.acquire();
        // printThird.run() outputs "third". Do not change or remove this line.
        printThird.run();
        
    }
}

实现思路基本上一样,都是控制线程等待和唤醒来控制方法的执行顺序。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值