JUC 线程按序打印ABCABCABC…
package thread.alternate;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/** * 线程交替打印 * 三个线程依次打印自己线程的名字 * 例如ABCABCABC... * * @author RhymeChiang * @date 2018/02/02 **/
public class ThreadAlternate {
/** * 1代表第一个线程 * 2代表第二个线程 * 3代表第三个线程 */
private int threadNo = 1;
// 创建一个同步锁
private Lock lock = new ReentrantLock();
// 代表第一个线程的通信
private Condition condition1 = lock.newCondition();
// 代表第二个线程的通信
private Condition condition2 = lock.newCondition();
// 代表第三个线程的通信
private Condition condition3 = lock.newCondition();
/** * 打印A线程的名字 * * @param loopNo */
public void loopA(int loopNo) {
lock.lock();
try {
// 如果不是第一个线程,则等待
if (threadNo != 1) {
condition1.await();
}
//如果是第一个线程则打印这个线程的名字
System.out.print(Thread.currentThread().getName());
// 唤醒第二个线程
threadNo = 2;
condition2.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void loopB(int loopNo) {
lock.lock();
try {
// 如果不是第一个线程,则等待
if (threadNo != 2) {
condition2.await();
}
//如果是第一个线程则打印这个线程的名字
System.out.print(Thread.currentThread().getName());
// 唤醒第二个线程
threadNo = 3;
condition3.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void loopC(int loopNo) {
lock.lock();
try {
// 如果不是第一个线程,则等待
if (threadNo != 3) {
condition3.await();
}
//如果是第一个线程则打印这个线程的名字
System.out.print(Thread.currentThread().getName());
// 唤醒第二个线程
threadNo = 1;
condition1.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
ThreadAlternate alternate = new ThreadAlternate();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
alternate.loopA(i);
}
}
},"A").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
alternate.loopB(i);
}
}
},"B").start();
new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
alternate.loopC(i);
}
}
},"C").start();
}
}
测试结果: