**版權(quán)聲明:本文為小斑馬偉原創(chuàng)文章,轉(zhuǎn)載請(qǐng)注明出處!

Condition 接口描述了可能會(huì)與鎖有關(guān)聯(lián)的條件變量。這些變量在用法上與使用Object.wait 訪問的隱式監(jiān)視器類似,但提供了更強(qiáng)大的功能。需要特別指出的是,單個(gè)Lock 可能與多個(gè)Condition 對(duì)象關(guān)聯(lián)。為了避免兼容性問題,Condition 方法的名稱與對(duì)應(yīng)的Object 版本中的不同。
在Condition 對(duì)象中與wait、notify 和notifyAll 方法對(duì)應(yīng)的分別是await、signal 和signalAll。
Condition 實(shí)例實(shí)質(zhì)上被綁定到一個(gè)鎖上。要為特定Lock 實(shí)例獲得Condition 實(shí)例,請(qǐng)使用其newCondition() 方法。
/**
* 生產(chǎn)者和消費(fèi)者
* @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, "生產(chǎn)者 A").start();
new Thread(cus, "消費(fèi)者 B").start();
new Thread(pro, "生產(chǎn)者 C").start();
new Thread(cus, "消費(fèi)者 D").start();
}
//店員
class Clerk {
private int product = 0 ;
//進(jìn)貨
public synchronized void get() {
while(product >= 1){//為了避免虛假喚醒問題,應(yīng)該總是使用在循環(huán)中
System.out.println("產(chǎn)品已滿!");
try {
this.wait();
} catch (InterruptedException e) {
}
}
System.out.println(Thread.currentThread().getName() + " : " + ++product);
this.notifyAll();
}
//賣貨
public synchronized void sale() {// product = 0; 循環(huán)次數(shù):0
while (product <= 0) {
System.out.println("缺貨!");
try {
this.wait();
} catch (InterruptedException e) {
}
}
System.out
.println(Thread.currentThread().getName() + " : " + --product);
this.notifyAll();
}
//生產(chǎn)者
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();
}
}
}
//消費(fèi)者
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循環(huán),取消if else判斷。
使用Codition來控制線程通信:
/*
* 生產(chǎn)者消費(fèi)者案例:
*/
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, "生產(chǎn)者 A").start();
new Thread(con, "消費(fèi)者 B").start();
new Thread(pro, "生產(chǎn)者 C").start();
new Thread(con, "消費(fèi)者 D").start();
}
class Clerk {
private int product = 0;
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
// 進(jìn)貨
public void get() {
lock.lock();
try {
if (product >= 1) { // 為了避免虛假喚醒,應(yīng)該總是使用在循環(huán)中。
System.out.println("產(chǎn)品已滿!");
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();
}
}
// 生產(chǎn)者
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();
}
}
// 消費(fèi)者
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 個(gè)線程,這三個(gè)線程的ID 分別為A、B、C,每個(gè)線程將自己的ID 在屏幕上打印10 遍,要求輸出的結(jié)果必須按順序顯示。
如:ABCABCABC…… 依次遞歸。
/*
* 編寫一個(gè)程序,開啟 3 個(gè)線程,這三個(gè)線程的 ID 分別為 A、B、C,每個(gè)線程將自己的 ID 在屏幕上打印 10 遍,要求輸出的結(jié)果必須按順序顯示。
* 如: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; //當(dāng)前正在執(zhí)行線程的標(biāo)記
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
/**
* @param totalLoop : 循環(huán)第幾輪
*/
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();
}
}