Java 多執行緒學習筆記(三)-守護執行緒

極客on之路發表於2016-07-03
package test.run;

import testpackage.MyThread;

public class Run {
	public static void main(String[] args) {
		try {
			MyThread thread = new MyThread();
			thread.setDaemon(true);
			thread.start();
			Thread.sleep(5000);
			System.out.println("我離開thread物件也不再列印了,也就是停止了!");
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
package testpackage;

public class MyThread extends Thread {
	private int i = 0;

	@Override
	public void run() {
		try {
			while (true) {
				i++;
				System.out.println("i=" + (i));
				Thread.sleep(1000);
			}
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
i=1
i=2
i=3
i=4
i=5

我離開thread物件也不再列印了,也就是停止了!





相關文章