天天看點

synchronized-順序輸出

程式設計要求

請仔細閱讀右側代碼,在 Begin-End 區域内進行代碼補充,使線程依照先後順序依次輸出JavaThread+線程名。

測試說明

測試輸入:無;

預期輸出:

JavaThreadAA

JavaThreadBB

JavaThreadCC

JavaThreadAA

JavaThreadBB

JavaThreadCC

JavaThreadAA

JavaThreadBB

JavaThreadCC

JavaThreadAA

JavaThreadBB

JavaThreadCC

JavaThreadAA

JavaThreadBB

JavaThreadCC

下面展示一些

内聯代碼片

package step1;

public class Task {
	public static void main(String[] args) throws Exception {
		/********* Begin *********/
		//在這裡建立線程, 開啟線程
	
Object a=new Object();
		Object b=new Object();
		Object c=new Object();
	MyThread t1 = new MyThread("AA",a,b);
	MyThread t2 = new MyThread("BB",b,c);
	MyThread t3 = new MyThread("CC",c,a);
	new Thread(t1).start();
	//t1.start();
	Thread.sleep(100);
	new Thread(t2).start();
	//t2.start();
	Thread.sleep(100);
	new Thread(t3).start();
	//t3.start();
	Thread.sleep(100);

		
		/********* End *********/
	}
}

class MyThread extends Thread {
	/********* Begin *********/
	Object prev;
	Object self;
	
	String threadName;
	public MyThread(String threadName,Object prev,Object self) {
		this.threadName=threadName;
		this.prev=prev;
		this.self=self;
	}

	public void run() {
		int count = 5;
		
		while(count > 0){
			synchronized(prev) {
				synchronized(self) {
					System.out.println("Java Thread" + this.threadName);
			count--;
			self.notify();
				}
				try {
					prev.wait();
				}catch(Exception e) {
				e.printStackTrace();	
				}
			}		
		}
		System.exit(0);
	
	}


	/********* End *********/
}