java线程间通信 notify wait

wait代码:this

public class WaitClass extends Thread{
    private List<Integer> list;
    private byte[] lock;

    public WaitClass(List list,byte[] lock){
        this.list = list;
        this.lock = lock;
    };

    public void run() {
         synchronized (lock){
             System.out.println("进入wait方法");
                 try {
                     lock.wait();
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
            System.out.println("走出wait方法");
         }
    }
}

notify代码:spa

public class NotifyClass extends Thread{
    private List list;
    private byte[] lock;

    public NotifyClass(List list,byte[] lock){
        this.list = list;
        this.lock = lock;
    }

    public void run() {
        synchronized (lock){
            for(int i=0;i<10;i++){
                list.add(i);
                try {
                    Thread.currentThread().sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if(list.size()==5){
                    lock.notify();
                }
                System.out.println("notify" + i);
            }
        }
    }
}

执行代码:code

public class MainClass {
    public static void main(String[] args){
        byte[] lock = new byte[0];
        List list = new ArrayList();
        NotifyClass notifyClass = new NotifyClass(list,lock);
        final WaitClass waitClass = new WaitClass(list,lock);
        waitClass.start();
        System.out.println("执行");
        notifyClass.start();
    }
}

结果:it

执行
进入wait方法
notify0
notify1
notify2
notify3
notify4
notify5
notify6
notify7
notify8
notify9
走出wait方法
 io

说明:class

  1. wait,notify必需要在synchronized中使用
  2. notify只能唤醒拥有相同锁的wait
  3. 只有执行完notifysynchronized代码块中的代码以后,才能执行被唤醒的wait的方法
相关文章
相关标签/搜索