1. 程式人生 > >java多執行緒相關知識點

java多執行緒相關知識點

1.sleep和wait的區別

執行緒狀態圖
(1).sleep是Thread中的靜態方法,誰呼叫誰去睡覺,即使在T1執行緒裡呼叫了T2執行緒的sleep方法,
實際上還是T1去睡覺。
(2)sleep方法不會釋放物件得鎖,而wait方法釋放了鎖.
(3)wait,notify和notifyAll只能在同步控制方法或者同步控制塊裡面使用,而sleep可以在任何地方使用。

2.多執行緒練習

(1)子執行緒迴圈10次,接著主執行緒迴圈100,接著又回到子執行緒迴圈10次,接著再回到主執行緒又迴圈100,如此迴圈50次,請寫出程式。

public class Test {

	public static void main(String[] args) {

		MyThread myThread = new MyThread();

		new Thread(new Runnable() {

			@Override
			public void run() {
				for (int i = 0; i < 50; i++) {
					try {
						myThread.subThread(i);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}).start();
		
		
		for(int i = 0; i < 50; i++) {
			try {
				myThread.mainThread(i);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}

class MyThread {

	private boolean isSubThread = true;

	public synchronized void subThread(int i) throws InterruptedException {

		if (!isSubThread) {
			this.wait();
		}

		for (int j = 0; j < 10; j++) {
			System.out.println("這是subThread>>>>" + i + "次迴圈," + "loop>>>" + j);
		}

		isSubThread = false;
		this.notify();
	}

	public synchronized void mainThread(int i) throws InterruptedException {

		if (isSubThread) {
			this.wait();
		}

		for (int j = 0; j < 100; j++) {
			System.out.println("這是MainThread>>>>" + i + "次迴圈," + "loop>>>" + j);
		}

		isSubThread = true;
		this.notify();
	}

}

未完待續…