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 基本使用重點>

沒有留言:

張貼留言