public class ConditionCommunication {
public static void main(String[] args) {
final Bussiness bussiness = new Bussiness();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 50;i++){
bussiness.father(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 50;i++){
bussiness.grandson(i);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i = 0;i < 50;i++){
bussiness.son(i);
}
}
}).start();
}
static class Bussiness{
private static int qu = 1;
Lock lock = new ReentrantLock();
Condition father = lock.newCondition();
Condition son = lock.newCondition();
Condition grandson = lock.newCondition();
public void father(int i){
lock.lock();
try{
while(qu != 1){
father.await();
}
for(int j = 0;j < 10;j++)
System.out.println("第" + i + "次循环=============" + "father线程第" + j + "次循环");
qu = 2;
son.signal();
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void son(int i){
lock.lock();
try{
while(qu != 2){
son.await();
}
for(int j = 0;j < 20;j++){
System.out.println("第" + i + "次循环=============" + "son线程第" + j + "次循环");
}
qu = 3;
grandson.signal();
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
public void grandson(int i){
lock.lock();
try{
while(qu != 3){
grandson.await();
}
for(int j = 0;j < 20;j++){
System.out.println("第" + i + "次循环=============" + "grandson线程第" + j + "次循环");
}
qu = 1;
father.signal();
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
lock.unlock();
}
}
}
}
Lock与Condition应用(三个线程之间通信问题)
最新推荐文章于 2021-10-31 15:11:53 发布