一、题目
编写一个程序,开启 3 个线程,这三个线程的ID 分别为A、B、C,每个线程将自己的ID 在屏幕上打印 10 遍 ,要求输出结果必须按顺序显示。
二、代码
package com.gf.demo;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class TestABCAlternate {
public static void main(String args[]) {
Alternate ad = new Alternate();
new Thread( new Runnable() {
@Override
public void run() {
for (int i = 1 ; i <= 10 ; i ++) {
ad.loopA(i);
}
}
} , "A").start();
new Thread( new Runnable() {
@Override
public void run() {
for (int i = 1 ; i <= 10 ; i ++) {
ad.loopB(i);
}
}
} , "B").start();
new Thread( new Runnable() {
@Override
public void run() {
for (int i = 1 ; i <= 10 ; i ++) {
ad.loopC(i);
}
}
} , "C" ).start();
}
}
class Alternate {
private int number = 1;
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition();
public void loopA(int totalLoop) {
try {
lock.lock();
//1. 判断
if (1 != number ) {
try {
condition1.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2. 打印
System.out.println(Thread.currentThread().getName());
number = 2;
condition2.signal();
} finally {
lock.unlock();
}
}
public void loopB(int totalLoop) {
try {
lock.lock();
//1. 判断
if (2 != number ) {
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2. 打印
System.out.println(Thread.currentThread().getName());
number = 3;
condition3.signal();
} finally {
lock.unlock();
}
}
public void loopC(int totalLoop) {
try {
lock.lock();
//1. 判断
if (3 != number ) {
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//2. 打印
System.out.println(Thread.currentThread().getName());
System.out.println("-------------------"+ "第 " + totalLoop + " 遍");
number = 1;
condition1.signal();
} finally {
lock.unlock();
}
}
}