随笔:wait sleep notify notifyAll

有什么错误,请指正,共同学习
### wait sleep notify notifyAll
#### 1、sleep依旧占用锁
#### 2、wait释放锁
#### 3、wait notify notify 必须在锁内执行
#### 4、notify只有一个线程能够执行下去,具体哪个线程,如果没有优先级,则随机
#### 5、notifyAll 所有线程都会获得锁、继续执行下去
#### 6、wait不能保证时间到或者notify了立即执行,只会去请求锁

代码

public class WaitTest {

    private static final List<Integer> list=new ArrayList<Integer>();

    public static void main(String[] args) throws InterruptedException {
        System.out.println("main.begin."+getTime());
        for (int i = 0; i < 10; i++) {
            final int finalI = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        add(finalI);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
        Thread.sleep(5000);
        synchronized (list) {
            list.notify();
//            list.notifyAll();
        }
        System.out.println("main.end."+getTime());
    }

    private static void add(int i) throws InterruptedException {
        synchronized (list) {
            System.out.println("add" + i + ".wait." + getTime());
            list.wait();
            System.out.println("add" + i + ".run.begin." + getTime());
            list.add(1);
            Thread.sleep(1000);
            System.out.println("add" + i + ".run.end." + getTime());
        }

    }
    private static String getTime() {
        return new SimpleDateFormat("mmssSSS").format(new Date());
    }
}

结果

// notifyAll
main.begin.0817944
add1.wait.0817945
add2.wait.0817946
add5.wait.0817946
add6.wait.0817946
add9.wait.0817946
add0.wait.0817946
add4.wait.0817947
add8.wait.0817947
add3.wait.0817947
add7.wait.0817947
main.end.0822946
add7.run.begin.0822946
add7.run.end.0823947
add3.run.begin.0823947
add3.run.end.0824947
add8.run.begin.0824947
add8.run.end.0825948
add4.run.begin.0825949
add4.run.end.0826949
add0.run.begin.0826949
add0.run.end.0827950
add9.run.begin.0827950
add9.run.end.0828950
add6.run.begin.0828950
add6.run.end.0829951
add5.run.begin.0829951
add5.run.end.0830952
add2.run.begin.0830952
add2.run.end.0831952
add1.run.begin.0831952
add1.run.end.0832953

// notify 程序未结束
main.begin.2422235
add0.wait.2422236
add1.wait.2422237
add2.wait.2422237
add4.wait.2422237
add5.wait.2422237
add9.wait.2422237
add6.wait.2422237
add7.wait.2422237
add3.wait.2422237
add8.wait.2422237
add0.run.begin.2427238
main.end.2427238
add0.run.end.2428239
    原文作者:CrazyGod
    原文地址: https://www.jianshu.com/p/cd9d202e1fdf
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞