启动三个线程:AA、BB、CC
- AA打印5次,BB打印5次,CC打印5次
- 重复10轮
解决方案:指定标识
class ThreadResource{
private int flag=1;//AA:1 BB:2 CC:3
private Lock lock=new ReentrantLock();
//为什么要创建三个condition?上一个例子是创建一个condition,唤醒所有的线程
//这里创建三个condition,通知下一个要执行的线程的condition
private Condition c1=lock.newCondition();
private Condition c2=lock.newCondition();
private Condition c3=lock.newCondition();
public void print5(int loop) throws InterruptedException {
//上锁
lock.lock();
try {
while(flag!=1){
c1.await();//等待
}
for(int i=1;i<=5;i++){
System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
}
flag=2;//修改标志位
c2.signal();//通知BB线程
}finally {
lock.unlock();
}
}
public void print10(int loop) throws InterruptedException {
//上锁
lock.lock();
try {
while(flag!=2){
c2.await();//等待
}
for(int i=1;i<=10;i++){
System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
}
flag=3;//修改标志位
c3.signal();//通知CC线程
}finally {
lock.unlock();
}
}
public void print15(int loop) throws InterruptedException {
//上锁
lock.lock();
try {
while(flag!=3){
c3.await();//等待
}
for(int i=1;i<=15;i++){
System.out.println(Thread.currentThread().getName()+"::"+i+"第"+loop+"轮");
}
flag=1;//修改标志位
c1.signal();//通知BB线程
}finally {
lock.unlock();
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
ThreadResource threadResource = new ThreadResource();
new Thread(()->{
for(int i=1;i<=10;i++){
try {
threadResource.print5(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"AA").start();
new Thread(()->{
for(int i=1;i<=10;i++){
try {
threadResource.print10(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"BB").start();
new Thread(()->{
for(int i=1;i<=10;i++){
try {
threadResource.print15(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"CC").start();
}
}