文章目录
问题描述
面试题:据说写出来,工资多加6K。。。。
- 编写一个程序,开启3个线程,这三个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要打印输出的结果必须按顺序显示。如:ABCABCABC… 依次递归
- demo
public class TestABCAlternate {
public static void main(String[] args) {
AlternateDemo ad = new AlternateDemo();
//现实用的时候多为这种形式
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 AlternateDemo{
private int number = 1;//当前正在执行线程的标记
private Lock lock = new ReentrantLock();
private Condition condition1 = lock.newCondition();//需要3个线程通信因为有3个线程
private Condition condition2 = lock.newCondition();//
private Condition condition3 = lock.newCondition();//
/**
*
* @param totalLoop 循环第几轮
*/
public void loopA(int totalLoop) {
lock.lock();
try {
//1.判断
while(number != 1) {//当标志不等于1的时候 线程A 等待
try {
condition1.await();//进入等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 1 ; i++) {
//2. 打印
System.out.println(Thread.currentThread().getName() + "\t"+ i + "\t" + totalLoop);
}
//3.唤醒
number = 2;//修改标志位B的标志
condition2.signal();//唤醒第二个线程,在其condition2.await()的地方
} finally {
lock.unlock();
}
}
public void loopB(int totalLoop) {
lock.lock();
try {
//1.判断
while(number != 2) {
try {
condition2.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 1 ; i++) {
//2. 打印
System.out.println(Thread.currentThread().getName() + "\t"+ i + "\t" + totalLoop);
}
//3.唤醒
number = 3;
condition3.signal();//唤醒第三个线程,在其condition3.await()的地方
} finally {
lock.unlock();
}
}
public void loopC(int totalLoop) {
lock.lock();
try {
//1.判断
while(number != 3) {
try {
condition3.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 1 ; i++) {
//2. 打印
System.out.println(Thread.currentThread().getName() + "\t"+ i + "\t" + totalLoop);
}
//3.唤醒
number = 1;
condition1.signal();//唤醒第一个线程,在其condition1.await()的地方
System.out.println("---------------");
} finally {
lock.unlock();
}
}
}