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();
}
}
}
}
顺序打印ABC,连续打10次
最新推荐文章于 2023-08-19 18:44:54 发布