1. 程式人生 > >多執行緒Runnable任務執行注意

多執行緒Runnable任務執行注意

public class ImplRunnable implements Runnable {
	String thread_name;
	int line = 10;//關鍵的共享變數
	@Override
	public void run() {
		synchronized (this){//確保每個任務只執行一次
		for(;0 < line;line--)
			System.out.println(Thread.currentThread().getName() + ":::::::::::" +line);
		}
	}
	
	public static void main(String[] args) {
		/**
		 * 共同執行一個任務,前提是有共享變數line
		 */
		ImplRunnable ir = new ImplRunnable();
		Thread th1 = new Thread(ir,"ImplRunnable001");
		Thread th2 = new Thread(ir,"ImplRunnable002");
		Thread th3 = new Thread(ir,"ImplRunnable003");
		th1.start();
		th2.start();
		th3.start();
		
		/**
		 * 每個thread都執行全部任務
		 */
		Thread th11 = new Thread(new ImplRunnable(),"ImplRunnable011");
		Thread th12 = new Thread(new ImplRunnable(),"ImplRunnable012");
		Thread th13 = new Thread(new ImplRunnable(),"ImplRunnable013");
		th11.start();
		th12.start();
		th13.start();
	}
}