面试题--三个线程循环打印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 
----------------- 

你可能感兴趣的:(多线程)