1. 程式人生 > >JAVA使用Lock與Condition實現排它,同步通訊

JAVA使用Lock與Condition實現排它,同步通訊

package com.study;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

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 {
    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
    private boolean isSync = true;

    public void ins() {
      lock.lock();
      try {
        while (!isSync) {
          condition.await();
        }
        Thread.sleep(1000L);
        System.out.println("正在上傳中....");
        isSync = false;
        condition.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally {
        lock.unlock();
      }
    }

    public void des() {
      lock.lock();
      try {
        while (isSync) {
          condition.await();
          Thread.sleep(1000L);
        }
        System.out.println("下載結束....");
        isSync = true;
        condition.signal();
      } catch (InterruptedException e) {
        e.printStackTrace();
      } finally{
        lock.unlock();
      }
    }
  }
}