Java 中的執行續可以分為兩種,一種是一般執行續,另一種為Daemon執行續。
Daemon Thread 的唯一用途就是為其他執行續提供服務,Daemon Thread 會隨時中斷,因此請勿將使用到需釋放之資源(如Input/Ouput Stream 、 DB Connector)的執行續 設定為 Daemon = True。
以下同時建立兩種執行續進行實驗:
1 2 3 4 5 6 7 8 9 10 |
public class Worker implements Runnable{ @Override public void run() { // TODO Auto-generated method stub for(int i=0;i<5;i++) System.out.println("第" + i + "次更新"); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class Timer implements Runnable{ @Override public void run() { // TODO Auto-generated method stub long currentTime = System.currentTimeMillis(); long processTime = 0; while(true) { if((System.currentTimeMillis() - currentTime) > processTime) { processTime = System.currentTimeMillis() - currentTime; System.out.println("程式執行時間 : " + processTime); } } } } |
透過setDaemon方法將執行續設置為Daemon Thread。
1 2 3 4 5 6 7 8 9 10 11 12 |
public class DaemonThreadTest { public static void main(String[] args) { // TODO Auto-generated method stub Thread userThread = new Thread(new Worker()); Thread daemonThread = new Thread(new Timer()); daemonThread.setDaemon(true); userThread.start(); daemonThread.start(); } } |
實驗結果如下:
文章標籤
全站熱搜
