Java新建線程的3種方法


Java新建線程的3種方法

===================

Java創建線程有3種方法:
(1)繼承Thread;
(2)實現Runnable接口;
(3)實現Callable接口;

 

由於Java只支持單繼承,所以用繼承的方式創建線程,比較死板,不夠靈活;用實現接口的方式創建線程,可以實現多個接口,比較靈活。
Runnable和Callable接口的區別:
(1)Callable重寫的方法是call(),Runnable重寫的方法是run();
(2)Callable的任務執行后可返回值,而Runnable不能返回值;
(3)call方法可以拋出異常,run()不可以;
(4)運行Callable任務可以拿到一個future對象,表示異步計算的結果,
它供檢查計算是否完成的方法,以等待計算完成,並檢索計算的結果。通過Future對象可以了解任務的執行情況,可取消任務的執行,還可以獲取執行的結果。

 

 

 

1.繼承Thread

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. public class ThreadClient {  
  4.   
  5.     public static void main(String[] args) {  
  6.         Print p1 = new Print();  
  7.         Print p2 = new Print();  
  8.         p1.start();  
  9.         p2.start();  
  10.   
  11.     }  
  12.   
  13. }  
  14.   
  15. class Print extends Thread{  
  16.     @Override  
  17.     public void run(){  
  18.         for(int i=0;i<10;i++){  
  19.             System.out.println(Thread.currentThread().getName()+":"+i);  
  20.             try {  
  21.                 Thread.sleep(2000);  
  22.             } catch (InterruptedException e) {  
  23.                 e.printStackTrace();  
  24.             }  
  25.         }  
  26.     }  
  27. }  

 

2.實現Runnable接口

 

/** 

 *    (1): 創建一個類,讓該類實現Runnable接口

 

 *    (2): 重寫run方法

 

  *    (3): 創建該類的對象

 

  *    (4): 創建Thread類的對象,然后把3中的對象作為參數傳遞給Thread

 

  *    (5): 啟動線程

 

  */

 

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. public class ThreadClient1 {  
  4.   
  5.     public static void main(String[] args) {  
  6.         Runnable p1 = new Salesman("Jack");  
  7.         Runnable p2 = new Salesman("Iris");  
  8.           
  9.         Thread t1 = new Thread(p1);  
  10.         Thread t2 = new Thread(p2);  
  11.           
  12.         t1.start();  
  13.         t2.start();  
  14.     }  
  15.   
  16. }  
  17.   
  18. class Salesman implements Runnable{  
  19.       
  20.     private int ticket=100;//每個線程都擁有100張票  
  21.     private String name;  
  22.     Salesman(String name){  
  23.         this.name=name;  
  24.     }  
  25.       
  26.     @Override  
  27.     public void run(){  
  28.         while(ticket>0){  
  29.              System.out.println(ticket--+" is saled by "+name+","+Thread.currentThread().getName());  
  30.             try {  
  31.                 Thread.sleep(1000);  
  32.             } catch (InterruptedException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.          }  
  36.     }  
  37. }  

 

3.實現Callable接口

[java]  view plain  copy
 
 
 
  1. package com.java.thread;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5. import java.util.concurrent.Callable;  
  6. import java.util.concurrent.ExecutionException;  
  7. import java.util.concurrent.ExecutorService;  
  8. import java.util.concurrent.Executors;  
  9. import java.util.concurrent.Future;  
  10.   
  11. public class CallType {  
  12.       
  13.     public static void main(String[] args) {  
  14.         ExecutorService es = Executors.newCachedThreadPool();  
  15.         List<Future<String>> results = new ArrayList<Future<String>>();  
  16.         for(int i=0;i<5;i++){  
  17.             results.add(es.submit(new TaskWithResult(i)));  
  18.         }  
  19.           
  20.         for(Future<String> fs : results){  
  21.             try {  
  22.                 System.out.println(fs.get());  
  23.             } catch (InterruptedException | ExecutionException e) {  
  24.                 // TODO Auto-generated catch block  
  25.                 e.printStackTrace();  
  26.             }  
  27.         }  
  28.     }  
  29. }  
  30.   
  31. class TaskWithResult implements Callable<String>{  
  32.     private int id;  
  33.     public TaskWithResult(int id){  
  34.         this.id = id;  
  35.     }  
  36.     @Override  
  37.     public String call() throws Exception {  
  38.         return "result of TaskWithResult" + id;  
  39.     }  
  40. }  

 

4.匿名內部類

/**  使用匿名內部類的方式實現 很少見

  *  new 類名/接口名() {

  *      方法重寫 ;

  *   } ;

  */

public class Thread4 {
public static void main(String[] args) {
//匿名實現多線程
//繼承thread類
new Thread(){
public void run(){
for(int x=0;x<111;x++){
System.out.println(getName()+":"+x);
}
}
}.start();
//實現runable
new Thread(new Runnable() {

@Override
public void run() {
for(int x=0;x<100;x++){
System.out.println("wwww");
}

}
}).start();
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM