顺序打印ABC,连续打10次

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

public class LoopWaitThreadTest {

static AtomicInteger count = new AtomicInteger(0);

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

public static void main(String[] args) {
LoopWaitThreadTest test = new LoopWaitThreadTest();
ThreadAAA a = test.new ThreadAAA("A");
ThreadBBB b = test.new ThreadBBB("B");
ThreadCCC c = test.new ThreadCCC("C");

a.start();
b.start();
c.start();
}

class ThreadAAA extends ThreadTemplates {

public ThreadAAA(String name) {
super(name);
}

public void dowork() {
try {
lock.lock();
/**
* 当调用newCondition.signalAll()时,会从newCondition.await()后面继续执行
* 所以必须要来个循环,否则会因为某些线程的此次循环早早的结束,而某些数字不能够消费掉导致死锁 例如:
* A线程判断一个数字时,也许他还不满足条件,然后他等待,当其他线程调用signalAll时,该线程被唤醒,但是马上此次循环就结束了,因为await下面没有可以执行的
*/
while (true) {
System.out.println("lock A");
if (LoopWaitThreadTest.count.intValue() % 3 == 0) {
System.out.println("A.....");
LoopWaitThreadTest.count.incrementAndGet();
newCondition.signalAll();
break;
} else {
try {
System.out.println("A wait");
// 当被唤醒时,从该方法之后开始执行
newCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

} finally {
System.out.println("unlock A");
lock.unlock();
}
}
}

class ThreadBBB extends ThreadTemplates {

public ThreadBBB(String name) {
super(name);
}

public void dowork() {
try {
lock.lock();
while (true) {
System.out.println("lock B");
if (LoopWaitThreadTest.count.intValue() % 3 == 1) {
System.out.println("B.....");
LoopWaitThreadTest.count.incrementAndGet();
newCondition.signalAll();
break;
} else {
try {
System.out.println("B wait");
newCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

} finally {
System.out.println("unlock B");
lock.unlock();
}

}

}

class ThreadCCC extends ThreadTemplates {

public ThreadCCC(String name) {
super(name);
}

public void dowork() {
try {
lock.lock();
System.out.println("lock C");
while (true) {
if (LoopWaitThreadTest.count.intValue() % 3 == 2) {
System.out.println("C.....");
LoopWaitThreadTest.count.incrementAndGet();
newCondition.signalAll();
break;
} else {
try {
System.out.println("C wait");
newCondition.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
} finally {
System.out.println("unlock C");
lock.unlock();
}
}
}

abstract class ThreadTemplates extends Thread {

public ThreadTemplates(String name) {
super();
this.setName(name);
}

abstract void dowork();

public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("current count is " + LoopWaitThreadTest.count.intValue());
dowork();
}
}

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值