`

Java多线程1--三线程打印ABC

    博客分类:
  • Java
 
阅读更多

建立3个线程,A线程打印10次A,B线程打印10次B,C线程打印10次C,要求线程同时运行,交替打印10次ABC

 

import java.util.concurrent.TimeUnit;

public class ThreadABC {

	public static void main(String[] args) throws InterruptedException {
		Object a = new Object();
		Object b = new Object();
		Object c = new Object();

		Thread pa = new Thread(new PrintThread("A", c, a)),
				pb = new Thread(new PrintThread("B", a, b)),
				pc = new Thread(new PrintThread("C", b, c));
		pa.start();
		TimeUnit.MILLISECONDS.sleep(100L);
		pb.start();
		TimeUnit.MILLISECONDS.sleep(100L);
		pc.start();

	}

}

class PrintThread implements Runnable {
	private String name;
	private Object prev;
	private Object self;

	public PrintThread(String name, Object prev, Object self) {
		this.name = name;
		this.prev = prev;
		this.self = self;
	}

	@Override
	public void run() {
		int i = 10;
		while (i-- > 0) {
			try {
				synchronized (prev) {
					synchronized (self) {
						System.out.print(name);
						self.notify();
					}
					
					prev.wait();
				}
			} catch (InterruptedException e) {
				System.out.println("Interrupted");
			}
		}
	}
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics