三个线程交替打印1~99
如 t1,t2,t3线程打印如下
t1: 1
t2: 2
t3: 3
t1: 4
t2: …
具体实现
思路: 线程共享资源类,保证操作共享资源时加锁,每个线程执行一次打印之后唤醒下一个线程,并且保证结束打印后线程不能处于阻塞状态
public class PrintHundred {
public static void main(String[] args) {
Resource resource = new Resource();
List<Runnable> runList = new ArrayList<>();
runList.add(() -> {
resource.printNnm(resource.firstCondition, resource.secondCondition);
});
runList.add(() -> {
resource.printNnm(resource.secondCondition, resource.thridCondition);
});
runList.add(() -> {
resource.printNnm(resource.thridCondition, resource.firstCondition);
});
for (int i = 1; i <= runList.size(); i++) {
new Thread(runList.get(i - 1), "" + i).start();
}
}
static class Resource {
int num = 0; // 初始值
Lock lock = new ReentrantLock();
Condition firstCondition = lock.newCondition();
Condition secondCondition = lock.newCondition();
Condition thridCondition = lock.newCondition();
public void printNnm(Condition self, Condition next) {
lock.lock();
try {
// 打印到99
while (num < 99) {
num += 1;
System.out.println("线程" + Thread.currentThread().getName() + "打印num当前值" + num);
next.signal();
self.await();
}
// 最后一个打印99结束也要唤醒下一个线程,保证下一个线程不在阻塞状态
next.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}