創建線程的三種方法及其比較

想寫博客好久了,養成好習慣,第一篇!微笑

方法一:繼承Thread類創建線程類

注意:既然已經繼承了Thread,就不能再繼承其他類了哈(Java是單繼承呢)

         多個線程之間無法共享線程類的實例變量

public class FirstThread extends Thread {
private int i;//這個i是線程類的實例變量,不會被共享呢
public void run() {
for (; i < 100; i++) {
System.out.println(getName() + ":" + i);
}

}

public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
if (i == 20) {
new FirstThread().start();
new FirstThread().start();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}

}

方法二:實現Runnable接口創建線程類

注意:Runnable實現類的run()方法是線程的執行體,注意Runnable對象只是作爲Thread對象的target,實際的線程對象仍然是Thread實例。如果兩個線程共享同一個target,那麼也就共享了該Runnable類的實例變量。

public class SecondThread implements Runnable{
private int i;
public void run() {
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
public static void main(String[] args) {
SecondThread st=new SecondThread();
for (int i = 0; i < 100; i++) {
if (i == 20) {
new Thread(st,"線程1").start();
new Thread(st,"線程2").start();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
}
}

方法三:實現Callable接口創建線程類

注意:這種方法和第二種很像,Callable接口提供了一個call()方法作爲線程執行體。

和run()方法相比,call()方法有返回值,可以聲明拋出異常。

Callable接口的實現類不可以作爲Thread對象的target,所以Java 5提供了一個Future接口來代表call()方法的返回值。

FutureTask類既實現了Future接口,又實現了Runnable接口,可以作爲Thread對象的target。所以可以通過FutureTask來包裝Callable對象。

public class ThirdThread {
public static void main(String[] args) {
FutureTask<Integer> task = new FutureTask<Integer>(new Callable<Integer>() {
int i=0;
public Integer call() throws Exception {
for (; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + ":" + i);
}
return i;
}
});
for (int i = 0; i < 100; i++) {
if (i == 20) {
new Thread(task,"有返回值的線程").start();
}
System.out.println(Thread.currentThread().getName() + ":" + i);
}
        try {
System.out.println("返回值是"+task.get());//調用get方法會導致主線程被阻塞
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
        System.out.println("main線程結束了");
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章