- 首页 > it技术 > >
并发面试题 三条线程同时启动,顺序打印abc十遍ReentrantLock Condition实现
package cn.wukala.wk;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Test {
privatestatic CountDownLatch countDownLatch =new CountDownLatch(1);
private static ReentrantLock reentrantLock = new ReentrantLock();
private static String now = "a";
static Condition ca = reentrantLock.newCondition();
static Condition cb = reentrantLock.newCondition();
static Condition cc = reentrantLock.newCondition();
public static void main(String[] args) {
Thread b= new Thread(new Worker("b"));
Thread a= new Thread(new Worker("a"));
Thread c= new Thread(new Worker("c"));
a.start();
b.start();
c.start();
countDownLatch.countDown();
}
static class Worker implements Runnable{
String s;
Worker(String s){
this.s=s;
}@Override
public void run() {
try {
countDownLatch.await();
// 等待其它线程
System.out.println(s+"启动");
reentrantLock.lock();
if(!s.equals(now)){//不是你的请放手
if(s.equals("a")){
ca.await();
}else if(s.equals("b")){
cb.await();
}else {
cc.await();
}
}
for(int i=0;
i<10;
i++){
System.out.println(s);
if(s.equals("a")){
now="b";
cb.signal();
ca.await();
}else if(s.equals("b")){
now="c";
cc.signal();
cb.await();
}else {
now="a";
ca.signal();
cc.await();
}}} catch (InterruptedException e) {
e.printStackTrace();
}finally {
reentrantLock.unlock();
}
}
}}
推荐阅读