记录下多线的题目

谁说我不能喝 提交于 2020-04-06 21:41:44

import java.util.*; import java.util.concurrent.TimeUnit;

A 线程添加10个元素,B线程监视当A线程添加了5个元素则结束

public class Test { volatile List<Object> list= new ArrayList();

public void add(Object o){
    list.add(o);
}

public int size(){
    return list.size();
}
public static void main(String args[]) {
    Test c = new Test();
    final Object lock = new Object();

        new Thread(() -> {
            synchronized (lock) {
                if (c.size() != 5) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
                System.out.println("t2 is end");


            }

        }, "t2").start();


    new Thread(() -> {
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                c.add(new Object());
                System.out.println("add" + i);
                if (c.size() == 5) {
                  lock.notify();
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }


                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

    }, "t1").start();

}

}

public class Test2 {

List<Object> list= new ArrayList();

public void add(Object o){
    list.add(o);
}

public int size(){
    return list.size();
}

public static void main(String[] args) {
    Test2 test2 = new Test2();
    CountDownLatch latch = new CountDownLatch(1);

    new Thread(()->{
        if(test2.size()!=5) {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    },"t2");


    new Thread(()->{
        for (int i = 0; i <10 ; i++) {
            test2.add(new Object());
            System.out.println("add"+i);
            if(test2.size()==5)
                latch.countDown();

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }


    },"t1");
}

}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!