1、多线程之间按照顺序调用,实现A->B->C 三个线程启动
AA打印5次,BB打印10次,CC打印15次;紧接着,AA打印5次,BB打印10次,CC打印15次。。。。。依次来十轮。
public class ShareResource {
private int number = 1; // a:1 b:2 c:3
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
// a干完后等待,唤起b
public void print5() {
lock.lock();
try {
// 1、判断
while (number != 1) {
c1.await();
}
// 2、干活
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 3、通知
number=2;
c2.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// b干完后等待,唤起c
public void print10() {
lock.lock();
try {
// 1、判断
while (number != 2) {
c2.await();
}
// 2、干活
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 3、通知
number=3;
c3.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
// c干完后等待,唤起a
public void print15() {
lock.lock();
try {
// 1、判断
while (number != 3) {
c3.await();
}
// 2、干活
for (int i = 0; i < 15; i++) {
System.out.println(Thread.currentThread().getName() + "\t" + i);
}
// 3、通知
number=1;
c1.signal();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
/**
* @description:多线程之间按照顺序调用,实现A->B->C 三个线程启动,要求如下:
* <p>
* AA打印5次,BB打印10次,CC打印5次;
* 紧接着,
* AA打印5次,BB打印10次,CC打印15次
* 。。。。。依次来十轮
* @Author: wangchao
* @Date: 2021/7/25
*/
public class Test01 {
public static void main(String[] args) {
ShareResource shareResource = new ShareResource();
// A线程循环了10次,但是第一个循环执行完后便进入的wait阶段,并唤起B,后面9次循环都没开始
new Thread(()->{
for (int i = 0; i < 10; i++) {
shareResource.print5();
}
},"A").start();
// B第一次循环直接进入wait,等被A唤醒后,完成第一次循环,并唤起C,后面9次循环都没开始
new Thread(()->{
for (int i = 0; i < 10; i++) {
shareResource.print10();
}
},"B").start();
// C第一次循环直接进入wait,等被B唤醒后,完成第一次循环,并唤起A,后面9次循环都没开始
new Thread(()->{
for (int i = 0; i < 10; i++) {
shareResource.print15();
}
},"C").start();
}
}