1. 程式人生 > >一個執行緒控制另一個執行緒的暫停或啟動

一個執行緒控制另一個執行緒的暫停或啟動

MainTest類中可以控制執行緒的暫停或繼續執行。

public class MainTest {

	/**
	 * 這個執行緒操作另一個執行緒的暫停或開始
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Thread1 th1 = new Thread1();
		Thread t1 = new Thread(th1);
		t1.start();
		try {
			Thread.sleep(20);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//thread執行緒暫停
		th1.wait1();
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//thread執行緒繼續執行
		th1.start1();
		//th1.wait1();
		//th1.start1();
	}

}

下面是thread類

public class Thread1 implements Runnable {
	private String flag = "start";
	private String control = "";

	public void run() {
		// TODO Auto-generated method stub
		int i = 0;
		while (true) {
			if (flag.equals("start")) {
				i++;
				System.out.println("The thread1 is running" + i);
			} else if (flag.equals("wait")) {
				try {
					System.out.println("===wait===");
					synchronized (control) {
						control.wait();
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	public void wait1() {
		this.flag = "wait";
	}

	public void start1() {
		this.flag = "start";
		if (flag.equals("start")) {
			synchronized (control) {
				control.notifyAll();
			}
		}
	}

}
定義了一個標誌位。還利用了synchronized同步關鍵字