2013年6月7日 星期五

Thread 02 基本使用重點

延續上一篇 <Thread 基本建構方法>

使用thread請不要override start() method , 執行時請用start();

創建一個Thread 如果有使用
Thread t1 = new Thread(xxx);
或是
Thread t1 = new Thread(){public void run(){...}};
使用下列程式碼,即可即可run執行緒
t1.start();
...但是如果使用
t1.run();
會發生甚麼事情呢....?

只能說這絕對不是你想要使用的執行緒方式

我很無聊的測試很多種組合之後,得到一個重點:

使用thread請不要override start() method , 執行時請用start();

至於我的測試結果是甚麼呢...有空再說吧Orz

2013年6月6日 星期四

Thread 01 基本建構方法

建立執行緒主要有三種方法:

 1. 繼承(extends)Thread 類別
class Mar1 extends Thread{
 public void run(){
  System.out.println("Hi");
}}
public class Type1 {
 public static void main(String argv[]){
  Mar1 mar1 =new Mar1();
  mar1.start();
}}
2. 實作(implements) Runnable 介面(interface) < 一定要實作run() >
class Mar2 implements Runnable{
 public void run(){
  System.out.println("Hi");
}}
public class Type2 {
 public static void main(String argv[]){
  Mar2 mar2 =new Mar();
  Thread t2 = new Thread(mar2);
  //請new一個Thread去接,不然找不到start()
  t2.start();
}}
 3. 使用匿名巢狀類別(anomymous nested class)
有幾種...
3-a:
public class Type3a {
 public static void main(String argv[]){
  Thread t3a =new Thread(new Runnable(){
   public void run(){
    System.out.println("Hi");
   }
  });
  t3a.start();
}}
或是讓Thread也匿名
3-b:
public class Type3b {
 public static void main(String argv[]){
  new Thread(new Runnable(){
   public void run(){
    System.out.println("Hi");
   }
  }).start();
}}
甚至連Runnable也不要了
3-c:
public class Type3c {
 public static void main(String argv[]){
  new Thread(){
   public void run(){
    System.out.println("Hi");
   }
  }.start();
}}
以上是基本建構方法,使用方法請看<Thread 基本使用重點>