java中實現多線程的三種方式(有/無返回值)

實現多線程有3種方法:繼承Thread類、實現Runnable接口、實現Callable接口(第三種變化可以參考http://blog.csdn.net/aboy123/article/details/38307539)

一、繼承Thread類

public class TestThread  extends Thread{

public void run(){

System.out.print(“啓動線程”);

}

public static void main(String args[]){

Thread th=new Thread();

th.start();

}

}

二、實現Runnable接口

public class TestRunnable implements Runnable{

public void run(){

System.out.print(“啓動線程”);

}

public static void main(String args[]){

TestRunnable tb=new TestRunnable();

Thread th=new Thread(tb);

th.run();

}

}

三、實現Callable接口

package test.querySystem.util;


import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
//不能在public 類中實現Callable接口
class TestResultThread implements Callable<String>{
private int id;
//有參數構造方法
public TestResultThread(int id){
this.id=id;
}
@Override
public String call() throws Exception {
return “線程任務返回值”+id;
}
}
public class TestThreadCallnable {
public static void main(String args[]) throws InterruptedException, ExecutionException{
//創建線程池
ExecutorService exec=Executors.newCachedThreadPool();
//創建線程容器
ArrayList<Future<String>> result=new ArrayList<Future<String>>();
//執行任務後返回結果,假如只有10個線程
for(int i=0;i<10;i++){
Future<String> f=exec.submit(new TestResultThread(i));
result.add(f);
}
//遍歷執行完成後的線程
for(Future<String> ft:result){
//判斷是否執行完成
if(ft.isDone()){
System.out.println(“完成的線程:”+ft.get());
}else{
System.out.println(“未完成的線程:”+ft);
}
}
//關閉線程池
exec.shutdown();
}
}

注意:1、如果不需要返回值,最好使用Runnable接口

    2、如果Executor後臺線程池還沒有完成,那麼這調用返回Future對象的get()方法,會阻塞直到計算完成。

            3、Callable規定Call()方法,而Runnable規定run()方法

    4、殺死進程最好就在類裏面調用destroy()方法;不要實例化後再殺死!因爲不知道線程到底什麼時候結束!

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