JUC執行緒高階---執行緒控制通訊Condition

weixin_34138377發表於2018-05-30

**版權宣告:本文為小斑馬偉原創文章,轉載請註明出處!

2878032-c69380da831f980d.png

Condition 介面描述了可能會與鎖有關聯的條件變數。這些變數在用法上與使用Object.wait 訪問的隱式監視器類似,但提供了更強大的功能。需要特別指出的是,單個Lock 可能與多個Condition 物件關聯。為了避免相容性問題,Condition 方法的名稱與對應的Object 版本中的不同。
在Condition 物件中與wait、notify 和notifyAll 方法對應的分別是await、signal 和signalAll。
Condition 例項實質上被繫結到一個鎖上。要為特定Lock 例項獲得Condition 例項,請使用其newCondition() 方法。

/**
  * 生產者和消費者
  * @author ZH-SW-Weiw
  *
  */
public class TestProductorAndConsumer {

public static void main(String[] args) {
    Clerk clerk = new Clerk();
    
    Productor pro = new Productor(clerk);
    Consumer cus = new Consumer(clerk);
    
    new Thread(pro, "生產者 A").start();
    new Thread(cus, "消費者 B").start();
    
    new Thread(pro, "生產者 C").start();
    new Thread(cus, "消費者 D").start();
}

 //店員
class Clerk {
private int product = 0 ;

//進貨
public synchronized void get() { 
    while(product >= 1){//為了避免虛假喚醒問題,應該總是使用在迴圈中
        System.out.println("產品已滿!");
        
        try {
            this.wait();
        } catch (InterruptedException e) {
        }
        
    }
    
    System.out.println(Thread.currentThread().getName() + " : " + ++product);
    this.notifyAll();
}

//賣貨
public synchronized void sale() {// product = 0; 迴圈次數:0
    while (product <= 0) {
        System.out.println("缺貨!");

        try {
            this.wait();
        } catch (InterruptedException e) {
        }
    }

    System.out
            .println(Thread.currentThread().getName() + " : " + --product);
    this.notifyAll();
}


//生產者
class Productor implements Runnable{
private Clerk clerk;

public Productor(Clerk clerk) {
    this.clerk = clerk;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
        
        clerk.get();
    }
}
}

 //消費者
class Consumer implements Runnable{
private Clerk clerk;

public Consumer(Clerk clerk) {
    this.clerk = clerk;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        clerk.sale();
    }
}
}

為了避免虛假喚醒問題,使用while迴圈,取消if else判斷。
使用Codition來控制執行緒通訊:

/*
 * 生產者消費者案例:
 */
public class TestProductorAndConsumerForLock {

public static void main(String[] args) {
    Clerk clerk = new Clerk();

    Productor pro = new Productor(clerk);
    Consumer con = new Consumer(clerk);

    new Thread(pro, "生產者 A").start();
    new Thread(con, "消費者 B").start();

    new Thread(pro, "生產者 C").start();
    new Thread(con, "消費者 D").start();
}
class Clerk {
private int product = 0;

private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();

// 進貨
public void get() {
    lock.lock();

    try {
        if (product >= 1) { // 為了避免虛假喚醒,應該總是使用在迴圈中。
            System.out.println("產品已滿!");

            try {
                condition.await();
            } catch (InterruptedException e) {
            }

        }
        System.out.println(Thread.currentThread().getName() + " : "
                + ++product);

        condition.signalAll();
    } finally {
        lock.unlock();
    }

}

// 賣貨
public void sale() {
    lock.lock();

    try {
        if (product <= 0) {
            System.out.println("缺貨!");

            try {
                condition.await();
            } catch (InterruptedException e) {
            }
        }

        System.out.println(Thread.currentThread().getName() + " : "
                + --product); 

        condition.signalAll();

    } finally {
        lock.unlock();
    }
}

// 生產者
class Productor implements Runnable {

private Clerk clerk;

public Productor(Clerk clerk) {
    this.clerk = clerk;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        clerk.get();
    }
}

// 消費者
class Consumer implements Runnable {

private Clerk clerk;

public Consumer(Clerk clerk) {
    this.clerk = clerk;
}

@Override
public void run() {
    for (int i = 0; i < 20; i++) {
        clerk.sale();
    }
}

執行緒按序交替開啟3 個執行緒,這三個執行緒的ID 分別為A、B、C,每個執行緒將自己的ID 在螢幕上列印10 遍,要求輸出的結果必須按順序顯示。
如:ABCABCABC…… 依次遞迴。

/*
 * 編寫一個程式,開啟 3 個執行緒,這三個執行緒的 ID 分別為 A、B、C,每個執行緒將自己的 ID 在螢幕上列印 10 遍,要求輸出的結果必須按順序顯示。
 *  如:ABCABCABC…… 依次遞迴
 */
public class TestABCAlternate {

public static void main(String[] args) {
    AlternateDemo ad = new AlternateDemo();
    
    new Thread(new Runnable() {
        @Override
        public void run() {
            
            for (int i = 1; i <= 20; i++) {
                ad.loopA(i);
            }
            
        }
    }, "A").start();
    
    new Thread(new Runnable() {
        @Override
        public void run() {
            
            for (int i = 1; i <= 20; i++) {
                ad.loopB(i);
            }
            
        }
    }, "B").start();
    
    new Thread(new Runnable() {
        @Override
        public void run() {
            
            for (int i = 1; i <= 20; i++) {
                ad.loopC(i);
                
                System.out.println("-----------------------------------");
            }
            
        }
    }, "C").start();
}

class AlternateDemo{

private int number = 1; //當前正在執行執行緒的標記

private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();

/**
 * @param totalLoop : 迴圈第幾輪
 */
public void loopA(int totalLoop){
    lock.lock();
    
    try {
        //1. 判斷
        if(number != 1){
            condition1.await();
        }
        
        //2. 列印
        for (int i = 1; i <= 1; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
        }
        
        //3. 喚醒
        number = 2;
        condition2.signal();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

public void loopB(int totalLoop){
    lock.lock();
    
    try {
        //1. 判斷
        if(number != 2){
            condition2.await();
        }
        
        //2. 列印
        for (int i = 1; i <= 1; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
        }
        
        //3. 喚醒
        number = 3;
        condition3.signal();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

public void loopC(int totalLoop){
    lock.lock();
    
    try {
        //1. 判斷
        if(number != 3){
            condition3.await();
        }
        
        //2. 列印
        for (int i = 1; i <= 1; i++) {
            System.out.println(Thread.currentThread().getName() + "\t" + i + "\t" + totalLoop);
        }
        
        //3. 喚醒
        number = 1;
        condition1.signal();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }
}

相關文章