三个线程ABC循环打印出ABCABCABCABC

有三个线程A,B,C 循环10次打印出三个线程的名字ABCABCABCABCABCABCABCABCABCABC

package com.lyl.test.thread;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ThreadTest {
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
private Condition conditionC = lock.newCondition();
private String threadPrintName = "A";

class A implements Runnable {
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (!Thread.currentThread().getName()
.equals(threadPrintName)) {
conditionA.await();
}
System.out.print(Thread.currentThread().getName());
threadPrintName = "B";
conditionB.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}

}
}

class B implements Runnable {
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (!Thread.currentThread().getName()
.equals(threadPrintName)) {
conditionB.await();
}
System.out.print(Thread.currentThread().getName());
threadPrintName = "C";
conditionC.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

class C implements Runnable {
public void run() {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (!Thread.currentThread().getName()
.equals(threadPrintName)) {
conditionC.await();
}
System.out.print(Thread.currentThread().getName());
threadPrintName = "A";
conditionA.signal();
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}

public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
Thread t1 = new Thread(tt.new A());
Thread t2 = new Thread(tt.new B());
Thread t3 = new Thread(tt.new C());
t1.setName("A");
t2.setName("B");
t3.setName("C");
t1.start();
t2.start();
t3.start();
}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值