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的方法
相關文章
相關標籤/搜索