1. 程式人生 > >java執行緒wait和notify 筆記理解

java執行緒wait和notify 筆記理解

首先明確 兩個的概念:

wait()方法是暫停使用當前鎖執行的執行緒,並釋放當前執行緒的資源和當前的物件鎖。

notify()方法是隨機喚醒使用當前鎖暫停的執行緒,而notifyAll()是喚醒所有的使用當前鎖暫停的執行緒

直接兩段程式碼 看看效果:

一個生產者執行緒往list新增一個string值,然後用兩個執行緒去消費remove掉。

public class Produce implements Runnable{

    public String obj;
    Produce(String obj){
        this.obj=obj;
    }
    @Override
    public void run() {
        synchronized (obj) {
            try {
                        System.out.println("開始生產");
                        ValueList.list.add("123");
                        obj.notifyAll();
                
            } catch (Exception e) {
                // TODO: handle exception
            }
         }
       }
}
 

消費者:

public class Comsumer implements Runnable{

    public String obj;
    Comsumer(String obj){
        this.obj=obj;
    }
    @Override
    public void run() {
        synchronized (obj) {
            try {
          
                    while(ValueList.list.size() == 0){
                        
                         System.out.println(Thread.currentThread().getName()+"開始進入阻塞");
                        obj.wait();

                  }

                       System.out.println(Thread.currentThread().getName()+"開始消費");
                        ValueList.list.remove(0);
                        System.out.println(ValueList.list.size());
     
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("異常"+Thread.currentThread().getName());            }
            
        }
        
    }

}

主函式:

public class PCMain {
    public static void main(String[] args) throws InterruptedException {
        String obj="";//這個就相當於鎖
        Comsumer com = new Comsumer(obj);
        Thread t1 = new Thread(com);
        t1.setName("one");
        Thread t2 = new Thread(com);
        t2.setName("two");
        
        t2.start();
        t1.start();
//        Thread.sleep(1000);這兒加上就是為了看到 消費者先消費會出現什麼效果


        Produce p = new Produce(obj);
        Thread t3 = new Thread(p);
        t3.start();
    }
}