看到网上有各种写法,但总感觉的看起来晦涩难懂。于是自己写了一个,如下:
【面试题--三个线程循环打印ABC 10次(另类解决方法)】
import java.util.concurrent.atomic.AtomicBoolean;
class Printer extends Thread
{
public AtomicBoolean canPrint;
private String _text;
private Printer _nextPrinter;
Printer(String name)
{
canPrint = new AtomicBoolean(false);
this._text = name;
} public void SetNextPrinter(Printer nextPrinter)
{
this._nextPrinter = nextPrinter;
}
@Override
public void run()
{
int count = 10;
while (count > 0)
{
if(canPrint.compareAndSet(true, false))
{
count--;
System.out.println(count +" - " + _text);
_nextPrinter.canPrint.set(true);
}
}
}
}public class TestPrinter
{
public static void main(String[] args)
{
Printer printerA = new Printer("A");
Printer printerB = new Printer("B");
Printer printerC = new Printer("C \n----------------- \n");
printerA.SetNextPrinter(printerB);
printerB.SetNextPrinter(printerC);
printerC.SetNextPrinter(printerA);
printerA.canPrint.set(true);
printerA.start();
printerB.start();
printerC.start();
return;
}
}
输出如下:
9 - A
9 - B
9 - C
-----------------
8 - A
8 - B
8 - C
-----------------
7 - A
7 - B
7 - C
-----------------
6 - A
6 - B
6 - C
-----------------
5 - A
5 - B
5 - C
-----------------
4 - A
4 - B
4 - C
-----------------
3 - A
3 - B
3 - C
-----------------
2 - A
2 - B
2 - C
-----------------
1 - A
1 - B
1 - C
-----------------
0 - A
0 - B
0 - C
-----------------
推荐阅读
- 代码狂魔|实战证明java中的两把锁ReentrantLock与synchronized的系统调用
- 进程通信方式
- 解决方案|大文件拆分方案的java实践
- 多线程编程(1)(共享内存与锁)
- Java|多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 一道面试题(多个线程按顺序输出)
- 多线程|java多线程实现奇偶数输出
- 用信号量(互斥锁)实现两个线程交替打印