java中建立線程的3種方法

1.繼承Thread類
優勢:能夠直接使用Thread類中的方法,代碼比較簡單。
缺點:繼承Thread類以後不能繼承其餘類。ide

2.實現Runable接口
優勢:實現接口,比影響繼承其餘類或實現接口。
缺點:函數

3.實現Callable接口
優勢:能夠獲取返回值,能夠拋出異常。
缺點:實現方法相對複雜測試

三種方法的實現例spa

public static void main(String[] args) throws InterruptedException, ExecutionException {
//繼承Thread類 線程

/*1.建立Thread類對象。
* 2.重寫run方法,添加在線程中執行的方法。
* 3.start方法啓動線程。
*/對象

new Thread() { 繼承

   public void run() 
     {
        for(int i=0;i<100;i++) { System.out.println(" 繼承Thread測試"+i); }接口

      } get

    }.start(); it

 

//實現Runnable接口

/*1.實現Runable接口。
* 2.重寫run方法,添加在線程中執行的方法。
* 3.建立thread類對象,Runable接口的實現做爲參數傳入,執行帶參數的構造函數。
* 4.start方法啓動線程。
*/

Runnable ra= new Runnable() {
@Override
public void run() { 
   for(int i=0;i<1000;i++)
  {System.out.println("Runnable線程測試 "+i);}
   }
};
Thread thread = new Thread(ra); 
thread.start(); 

 


//Callable

/*1.建立線程池。
* 2.現實Callable接口。
* 3.重寫Call方法,添加在線程中執行的方法。
* 4.把Callable的實現放到線程池中。並得到線程池返回的Future對象。
*/
ExecutorService es = Executors.newFixedThreadPool(3);
Callable<Integer> ca=new Callable<Integer>()
  {
   @Override
   public Integer call() throws Exception {
   return 100;
   }
};
Future<Integer> ft =es.submit(ca); 
System.out.println(ft.get());
es.shutdown();

}}

相關文章
相關標籤/搜索