给出一个题目,有3个线程,我希望线程1向控制台输出3行信息后,线程2向控制台输出6行信息,接下来是线程3输出10行信息到控制台,如此循环10次。在一个线程输出信息的时候,其他线程不能产生干扰。
package com.concurrent.condition;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*==================================
* 描述:有3个线程,线程1连续输出3次,然后让线程2连续输出6次,接下来线程3连续输出10次。依次循环10次
*
==================================*/
public class ConditionExample {public static void main(String[] args) {
final Outer outer = new Outer();
final int loopNum = 10;
// 线程1
new Thread(new Runnable() {@Override
public void run() {
for (int i = 1; i < loopNum; i++) {
outer.out1(i);
}
}
}).start();// 线程2
new Thread(new Runnable() {@Override
public void run() {
for (int i = 1; i < loopNum; i++) {
outer.out2(i);
}
}
}).start();// 线程3
new Thread(new Runnable() {@Override
public void run() {
for (int i = 1; i < loopNum; i++) {
outer.out3(i);
}
}
}).start();}
}
class Outer {
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();int currentNo = 1;
// 线程1的输出方法
public void out1(int loopNum) {
try {
lock.lock();
while (currentNo != 1) {
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 3; i++) {
System.out.println("this Thread1 outer no." + i + " ; loop="
+ loopNum);
}
currentNo = 2;//标志态置换为线程2可以输出的标志
condition2.signal();// 通知线程2开始了
} finally {
lock.unlock();
}
}//线程2的输出方法
public void out2(int loopNum) {
try {
lock.lock();
while (currentNo != 2) {
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 6; i++) {
System.out.println("this Thread2 outer no." + i + " ; loop="
+ loopNum);
}
currentNo = 3;//标志态置换为线程3可以输出的标志
condition3.signal();//通知线程3
} finally {
lock.unlock();
}
}//线程3的输出方法
public void out3(int loopNum) {
try {
lock.lock();
while (currentNo != 3) {
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 0; i < 10; i++) {
System.out.println("this Thread3 outer no." + i + " ; loop="
+ loopNum);
}
currentNo = 1;//标志态置换为线程2可以输出的标志
condition1.signal();//通知线程1
} finally {
lock.unlock();
}
}
}
Java如何实现线程之间的互斥,布布扣,bubuko.com