1. 程式人生 > >JAVA多執行緒使用synchronized與wait,notify實現排它,同步通訊

JAVA多執行緒使用synchronized與wait,notify實現排它,同步通訊

JAVA使用多執行緒實現上傳圖片,當上傳結束後,再通過另外一個執行緒告知下載圖片結束,這時候就需要用到synchronized以及wait,notify實現排它,同步通訊,上傳圖片時,不允許下載,因為此時圖片正在上傳。

package com.study;

public class Demo {
  
  public static void main(String[] args) {
    Demo demo = new Demo();
    final OutPutClass putPutClass = demo.new OutPutClass();
    Thread thread = new Thread(new Runnable() {
      
      @Override
      public void run() {
        while(true){
          putPutClass.ins();
        }
      }
    });
    thread.start();
    
    Thread thread2 = new Thread(new Runnable() {
      
      @Override
      public void run() {
        while(true){
          putPutClass.des();
        }
      }
    });
    thread2.start();
  }
  
  class OutPutClass{
    private boolean isSync = true;
    public synchronized void ins(){
      try {
        while(!isSync){
          this.wait();
        }
        Thread.sleep(1000L);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("正在上傳中....");
      isSync = false;
      this.notify();
    }
    public synchronized void des(){
      while(isSync){
        try {
          this.wait();
          Thread.sleep(1000L);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      System.out.println("下載結束....");
      isSync = true;
      this.notify();
    }
  }
}