使用Condition对象可以对线程执行的业务进行排序规划
public class Run {
private volatile static int nextPrintWho = 1;
private static ReentrantLock lock = new ReentrantLock();
private final static Condition conditionA = lock.newCondition();
private final static Condition conditionB = lock.newCondition();
private final static Condition conditionC = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
Thread threadA = new Thread(){
public void run() {
try {
lock.lock();
while (nextPrintWho != 1) {
conditionA.await();
}
for (int i=0; i<3; i++) {
System.out.println("ThreadA " + (i+1));
}
nextPrintWho = 2;
conditionA.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
Thread threadB = new Thread(){
public void run() {
try {
lock.lock();
while (nextPrintWho != 2) {
conditionB.await();
}
for (int i=0; i<3; i++) {
System.out.println("ThreadB " + (i+1));
}
nextPrintWho = 3;
conditionB.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
Thread threadC = new Thread(){
public void run() {
try {
lock.lock();
while (nextPrintWho != 3) {
conditionC.await();
}
for (int i=0; i<3; i++) {
System.out.println("ThreadC " + (i+1));
}
nextPrintWho = 1;
conditionC.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
};
Thread[] aArray = new Thread[5];
Thread[] bArray = new Thread[5];
Thread[] cArray = new Thread[5];
for (int i=0; i<5; i++) {
aArray[i] = new Thread(threadA);
bArray[i] = new Thread(threadB);
cArray[i] = new Thread(threadC);
aArray[i].start();
bArray[i].start();
cArray[i].start();
}
}
}
ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ThreadA 1 ThreadA 2 ThreadA 3 ThreadB 1 ThreadB 2 ThreadB 3 ThreadC 1 ThreadC 2 ThreadC 3 ...... |