线程按序交替
package com.yanxizhu;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* @description: 线程按序交替
* @date: 2022/3/19 14:47
* @version: 1.0
*/
public class PrintInfo {
public static void main(String[] args) {
print print = new print();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<5;i++){
try {
print.printA(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"A").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<5;i++){
try {
print.printB(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"B").start();
new Thread(new Runnable() {
@Override
public void run() {
for(int i=1;i<5;i++){
try {
print.printC(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
},"C").start();
}
}
class print{
private int num =1;
Lock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
Condition condition2 = lock.newCondition();
Condition condition3 = lock.newCondition();
public void printA(int i) throws InterruptedException {
lock.lock();
try{
if(num != 1){
condition1.await();
}
System.out.println("A=="+Thread.currentThread().getName()+"====i="+i);
num=2;
condition2.signal();
}finally {
lock.unlock();
}
}
public void printB(int i) throws InterruptedException {
lock.lock();
try{
if(num != 2){
condition2.await();
}
System.out.println("B=="+Thread.currentThread().getName()+"====i="+i);
num=3;
condition3.signal();
}finally {
lock.unlock();
}
}
public void printC(int i) throws InterruptedException {
lock.lock();
try{
if(num != 3){
condition3.await();
}
System.out.println("C=="+Thread.currentThread().getName()+"====i="+i);
num=1;
condition1.signal();
}finally {
lock.unlock();
}
}
}
打印结果:
A==A====i=1
B==B====i=1
C==C====i=1
A==A====i=2
B==B====i=2
C==C====i=2
A==A====i=3
B==B====i=3
C==C====i=3
A==A====i=4
B==B====i=4
C==C====i=4
评论 (0)