Java多線程之線程傳回值

來源:互聯網
上載者:User

對於Java多線程的理解,我以前僅僅局限於實現Runnable介面或者繼承Thread類,然後重寫run()方法,最後start()調用就算完事,但是一旦涉及死結以及對共用資源的訪問和隨時監控線程的狀態和執行順序等等就不行了,所以現在開始看Thinking in java的並發這一節,從頭學多線程,

       下面發一個關於線程中的任務返回,和建立線程池的代碼

   

package com.bird.thinking;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * @use 使用Executor顯示的建立Thread對象 * @author Bird * */class LiftOff implements Runnable{//建立一個類實現Runable介面protected int countDown = 10;private static int taskCount = 0;private final int id = taskCount++;public LiftOff(){}public LiftOff(int countDown){this.countDown = countDown;}public String status(){return "#"+id+"("+(countDown > 0 ? countDown : "Liftoff !" + ")");}public void run(){while(countDown-- > 0){System.out.println(status());Thread.yield();}}}public class CachedThreadPool {public static void main(String[] args){ExecutorService exec = Executors.newCachedThreadPool();//建立線程池for(int i = 0; i < 5; i++){exec.execute(new LiftOff());//進行工作}exec.shutdown();}}

Executor為執行器,將為你管理Thread對象,從而簡化了並發編


程。Executor在用戶端和任務執行之間提供了一個間接層,與客戶


端直接執行任務不同,這個中介對象將執行任務。Executor允許你


管理非同步任務的執行,而無需顯示的管理線程的生命週期。


Executor是Java SE6/7中啟動任務的優選方法。

下面的代碼就能夠隨時監控各個線程的狀態了

package com.bird.thinking;import java.util.ArrayList;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;/** * @use 建立從任務中傳回值的多線程,可以判斷他的狀態 * @author Bird * */class TaskWithResult implements Callable<String>{//實現這個介面,調用的是call()方法private int id;public TaskWithResult(int id){this.id  = id;}public String call(){return "result of TaskWithResult" + id;}}public class CallableDemo {public static void main(String[] args){ExecutorService exec = Executors.newCachedThreadPool();ArrayList<Future<String>>  results = new ArrayList<Future<String>>();for(int i = 0; i < 10; i++){results.add(exec.submit(new TaskWithResult(i)));}for(Future<String> fs : results){try{System.out.println(fs.get());//可以調用很多方法,包括是否工作等等}catch(Exception e){e.printStackTrace();}finally{exec.shutdown();}}}}

Submit方法會產生Future對象,他用Callable返回結果的特定類型


進行了參數化。你可以用isDemo()方法來查詢Future()是夠已經完


成。當任務完成的時候,他具有一個結果,你可以調用get()方法


獲得這個結果。




Java 6/7最佳的休眠方法為TimeUnit.MILLISECONDS.sleep(100);



最好不要用 Thread.sleep(100);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.