每個thread都關聯著一個實例class成為thread,有兩個基本的策略來使用Thread物件。
1. 直接控制thread製造和管理,單純實例化Thread每次當應用程式需要實例化一個非同步的工作。
2. 抽象thread管理從你的應用程式的剩餘,將應用程式的工作交給executor
定義以及開始Thread
一個應用程式製造出一個Thread實例應該要提供將會執行在Thread內的程式碼,有兩種方法來做
提供一個Runnable物件,Runnable介面定義一個簡單的方法run(),中間包含了要被thread執行的code
Runnable物件交給Thread建構子,如同下面的程式碼
public class HelloRunnable implements Runnable { public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new Thread(new HelloRunnable())).start(); // 將Runnable物件交給Thread建構子 } }
Subclass thread, thread class本身實做了Runnable,然而它的run方法沒有做任何事情,一個應用程式
可以繼承Thread,提供自己實做run,如同下面的例子
public class HelloThread extends Thread { //本class直接繼承Thread public void run() { System.out.println("Hello from a thread!"); } public static void main(String args[]) { (new HelloThread()).start(); } }
建議使用第一種implements Runnable方法會讓程式更加的彈性,在Thread類別下定義了許多有用的方法,不少的
static方法可以得到Thread本身的資訊,我們將會說明它們在等回兒的部份
參考網址:
http://java.sun.com/docs/books/tutorial/essential/concurrency/runthread.html
No comments:
Post a Comment