Friday, November 11, 2011

Java Programming Thread

什麼是 Thread?
Thread 翻成中文叫做執行緒。一個程式一般來說就是一個 Process, 會執行一個工作就是從 main( ) 或主程式(事實上是一個主執行緒)從第一行到最後一行,而執行緒可以讓程式可以同時執行好幾個工作。更清楚的解釋: http://en.wikipedia.org/wiki/Thread_(computer_science)

A multithreaded process with two threads executing in time clearly showing that the threads execute separately and execute mutually exclusively in time. [Source: http://en.wikipedia.org/wiki/File:Multithreaded_process.svg]


什麼時候要用到Thread?
當我們有很多動西要同時一起跑的時候就要用到Thread, 比如說你的程式要刷新畫面,同時也要下載東西,播放音樂,監聽事件(Event Listener 同時要有好幾個 while loop 在等待).

到底要 extends Thread 還是 implements Runnable (extends Thread VS implements Runnable)? 
The difference:

1)If you want to extend the Thread class then it will make your class unable to extend other classes as java is having single inheritance feature whereas If you implement runnable interface, you can gain better object-oriented design and consistency and also avoid the single inheritance problems.
2)Extending the thread will give you simple code structure in comparison to Runnable Interface.
3)Using Runnable Interface, you can run the class several times whereas Thread have the start() method that can be called only once.


Thread .setDaemon(true) 的方法(method)
如果設成Daemon則代表這個thread在背後執行

從Main函式開始的是一個非Daemon執行緒,如果您希望某個執行緒在非Daemon執行緒都結束後也跟著終止,那麼您要將它設定為Daemon執行 緒,下面這個程式是個簡單的示範: 
  • DaemonTest.java
package onlyfun.caterpillar;
 
public class DaemonTest { 
    public static void main(String[] args) { 
        Thread thread = new Thread(new Runnable() {
            public void run() { 
                while(true) { 
                    System.out.print("T"); 
                } 
            }        
        }); 
        thread.setDaemon(true); 
        thread.start(); 
    }
} 

No comments:

Post a Comment