多线程交替打印示例

时间:2022-07-13 18:36:16
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
* 可以实现指定的打印次数,和每次打印的个数,
* 按线程顺序进行交替打印,打印完之后会停止多线程
* 思路:不同线程类实现不同的逻辑,通过并发包下的原子类来进行控制停止的时机,
*     用condition 来进行控制不同线程之间的通信,用参数控制打印元素的个数和总共打印的轮数
*/
public class TestCondition {
public int signal ;
public ReentrantLock lock = new ReentrantLock();
public Condition conditionA = lock.newCondition();
public Condition conditionB = lock.newCondition();
public Condition conditionC = lock.newCondition();
public AtomicInteger shutdown = new AtomicInteger(5);
public int printANum;
public int printBNum;
public int printCNum;
public int printCount;
public TestCondition(int printANum,int printBNum,int printCNum,int printCount){
this.printANum = printANum;
this.printBNum = printBNum;
this.printCNum = printCNum;
this.printCount = printCount;
}
public void printA(){
try {
lock.lock();
while (signal!=0 ){
conditionA.await();
}
for (int i = 1; i<=printANum;i++){
System.out.print("A");
}
signal++;
conditionB.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printB(){
try {
lock.lock();
while (signal!=1 ){
conditionB.await();
}
for (int i = 1; i<=printBNum;i++){
System.out.print("B");
}
signal++;
conditionC.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printC(){
try {
lock.lock();
if (signal!=2 ){
conditionC.await();
}
for (int i = 1; i<=printCNum;i++){
System.out.print("C");
}
signal = 0;
conditionA.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}

public static void main(String[] args) {
TestCondition testCondition =
new TestCondition(1,1,1,5);
A a = new A(testCondition);
B b = new B(testCondition);
C c = new C(testCondition);

new Thread(a).start();
new Thread(b).start();
new Thread(c).start();
}
}

class A implements Runnable{
public TestCondition testCondition;
public A (TestCondition testCondition){
this.testCondition = testCondition;
}
public void run() {
while (testCondition.shutdown.get()>0){
testCondition.printA();
testCondition.shutdown.decrementAndGet();
}
}
}

class B implements Runnable {
public TestCondition testCondition;
public B (TestCondition testCondition){
this.testCondition = testCondition;
}
public void run() {
while (testCondition.shutdown.get()>0){
testCondition.printB();
}
}

}
class C implements Runnable {
public TestCondition testCondition;
public C (TestCondition testCondition){
this.testCondition = testCondition;
}
public void run() {
while (testCondition.shutdown.get()>0){
testCondition.printC();
}
}
}