Posted on 2007-08-01 18:46
尚愛軍 閱讀(150)
評論(0) 編輯 收藏
方法一:
1.定義線程類實現Runnable接口
2.Thread myThread = new Thread(target) //target 為Runnable接口類型。
3.Runnable中只有一個方法:public void run(); //用以定義線程云形體。
4.使用Runnable接口可以為多個線程提供共享的數據。
5.在實現Runnable接口的類的run方法定義中可以使用Thread靜態方法:
public static Thread currentThread()//獲取當前線程的引用。
舉例:
public class TestThread1() {
public static void main(String[] args) {
Runner1 r= new Runner1();
Thread t = new Thread(r);
t.start();
for(int i=0; i<100; i++) {
System.out.println("Main Thread:------" + i);
}
}
}
class Runner1 implements Runnable {
public void run() {
for (int i=0; i<100; i++) {
System.out.println("Runner1 :" + i);
}
}
}
方法二:
1.可以定義一個Thread的子類并重寫其run方法,如:
class MyThread extends Thread {
public void run() {......}
}
2.然后生成該類的對象:
MyThread myThread = new MyThread(......)
舉例:
public class TestThread (
public static void main(String[] args) {
Runner1 r = new Runner1();
r.start();
for(int i=0; i<100; i++) {
System.out.println("Main Thread:------" + i);
}
}
)
class Runner1 extends Thread {
public void run() {
for (int i=0; i<100; i++) {
System.out.println("Runner1 :" + i);
}
}
結論:使用第一種方法生成多線程好,因為一個類可以繼承多個接口。而類繼承只能是單繼承。