# condition实现三个线程顺序执行《2》

public class ThreeConditionCommunication {

/**
* @param args
*/
public static void main(String[] args) {

new Thread(new Runnable() {

@Override
public void run() {

for (int i = 1; i <= 50; i++) {
}
}
}).start();

new Thread(new Runnable() {

@Override
public void run() {

for (int i = 1; i <= 50; i++) {
}
}
}).start();

for (int i = 1; i <= 50; i++) {
}
}

static class Business {
Lock lock = new ReentrantLock();
//同上一个例子差不多，实现三个conditons 一个锁内部可以有多个Condition，即有多路等待和通知
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
private int shouldSub = 1;

public void sub2(int i) {
lock.lock();
try {
while (shouldSub != 2) {
try {
condition2.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub2 thread sequence of " + j
+ ",loop of " + i);
}
shouldSub = 3;
condition3.signal();
} finally {
lock.unlock();
}
}

public void sub3(int i) {
lock.lock();
try {
while (shouldSub != 3) {
try {
condition3.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 20; j++) {
System.out.println("sub3 thread sequence of " + j
+ ",loop of " + i);
}
shouldSub = 1;
condition1.signal();
} finally {
lock.unlock();
}
}

public void sub1(int i) {
lock.lock();
try {
while (shouldSub != 1) {
try {
condition1.await();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("sub1 thread sequence of " + j
+ ",loop of " + i);
}
shouldSub = 2;
condition2.signal();
} finally {
lock.unlock();
}
}
}
}

• 本文已收录于以下专栏：

## Java多线程与并发应用-(11)-用Lock+Condition实现1,2,3 三个模块按顺序执行。

package com.lipeng; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks....

## 使用Lock,Condition解决三个线程依次轮流打印出75个数

import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.uti...

## java使用三个线程，按顺序线程1输出1、线程2输出2、线程3输出3

import java.util.concurrent.locks.ReentrantLock; /** * 标题、简要说明. * 类详细说明. * * Copyright: Copyr...

## 启动三个线程A，B，C，打印10次 按照ABC的顺序输出

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util...

## JAVA多线程顺序执行（使用join，lock,condition，信号量）原理和java源代码

java多线程顺序执行问题 使用join 假设我要让3个线程按照顺序打印ABC，那么可以使用Join,如果要求多线程按顺序循环打印，则不能用join了 join关键字 join是Thread类的一个方...

举报原因： 您举报文章：condition实现三个线程顺序执行《2》 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)