package com.atimooc.com;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class ShareThread {
private int flag = 1;// flag作为标记
private Lock lock = new ReentrantLock();
private Condition c1 = lock.newCondition();
private Condition c2 = lock.newCondition();
private Condition c3 = lock.newCondition();
public void Test01() throws InterruptedException {
lock.lock();
try {
while (flag != 1) {
c1.await();
}
System.out.println("正在执行的是:" + Thread.currentThread().getName() + ";之后执行T2");
flag = 2;
c2.signal();// 通知一个线程来执行
} finally {
lock.unlock();
}
}
public void Test02() throws InterruptedException {
lock.lock();
try {
while (flag != 2) {
c2.await();
}
System.out.println("正在执行的是:" + Thread.currentThread().getName() + ";之后执行T3");
flag = 3;
c3.signal();// 通知一个线程来执行
} finally {
lock.unlock();
}
}
public void Test03() throws InterruptedException {
lock.lock();
try {
while (flag != 3) {
c3.await();
}
System.out.println("正在执行的是:" + Thread.currentThread().getName() + ";之后执行T1");
flag = 1;
c1.signal();// 通知一个线程来执行
} finally {
lock.unlock();
}
}
}
public class ThreadDemo {
public static void main(String[] args) {
ShareThread sh = new ShareThread(); //我使用的是JDK1.8,如果是1.8之前的版本,需要在类对象前面加final
new Thread(new Runnable() {
@Override
public void run() {
try {
sh.Test01();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "T1").start();
new Thread(new Runnable() {
@Override
public void run() {
try {
sh.Test02();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "T2").start();
new Thread(new Runnable() {
@Override
public void run() {
try {
sh.Test03();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "T3").start();
}
}
执行结果:
正在执行的是:T1;之后执行T2
正在执行的是:T2;之后执行T3
正在执行的是:T3;之后执行T1