【并发】线程通信面试题

2019-02-14  本文已影响0人  河神
image.png

我做的如下

public class T1 {

    List<Integer> list = new ArrayList<>();
    volatile  boolean flag = true;
    int i=1;
    Object o = new Object();

    public void m1(){
        while (true){
            synchronized (o){
                if(list.size()==10){
                    break;
                }
                if(list.size()<6){
                    if(!flag){
                        continue;
                    }
                }
                System.out.println("add "+i);
                list.add(i++);
                flag=false;

                if(list.size()<6){
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }
    }
    public void m2(){
        while (true){
            synchronized (o){
                if(!flag){
                    System.out.println(list.size());
                    flag=true;
                    o.notifyAll();
                    if(list.size()==5){
                        System.out.println("满足条件");
                        break;
                    }
                }
            }
        }
    }
    public static void main(String[] args) {
        T1 t = new T1();
        new Thread(()->t.m1()).start();
        new Thread(()->t.m2()).start();
    }

}

运行结果:


image.png

也可以使用:CountDownLatch 来做这道题

CountDownLatch类位于java.util.concurrent包下,利用它可以实现类似计数器的功能。比如有一个任务A,它要等待其他4个任务执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

上一篇 下一篇

猜你喜欢

热点阅读