Java multi-threading 1--three-thread printing ABC

Create 3 threads, A thread prints A 10 times, B thread prints 10 times B, and C thread prints 10 times C, requiring the threads to run at the same time, alternately printing ABC 10 times

 

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");
			}
		}
	}
}

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326583850&siteId=291194637