java多線程批量執行的時限問題

來源:互聯網
上載者:User

標籤:

需求:需要並發執行三個線程,要求在指定的時間內返回結果,如果某個線程逾時,則返回為空白。

思路:使用ExecutorService的invokeAll(time,timeUint)方法來設定執行時限,該方法返回一個List<Future<T>>,一旦返回後,即取消尚未完成的任務,然後再從list中讀取future並調用future.get()方法來擷取線程返回的結果,如果future.get()拋出CancellationException 則說明該任務未完成被取消了。

<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,                              long timeout,                              TimeUnit unit)                          throws InterruptedException執行給定的任務,當所有任務完成或逾時期滿時(無論哪個首先發生),返回保持任務狀態和結果的 Future 列表。返回列表的所有元素的 Future.isDone() 為 true。一旦返回後,即取消尚未完成的任務。注意,可以正常地或通過拋出異常來終止已完成 任務。如果此操作進行中時修改了給定的 collection,則此方法的結果是不確定的。 參數:tasks - 任務 collectiontimeout - 最長等待時間unit - timeout 參數的時間單位 返回:表示任務的 Future 列表,列表順序與給定工作清單的迭代器所產生的順序相同。如果操作未逾時,則已完成所有任務。如果確實逾時了,則某些任務尚未完成。 拋出: InterruptedException - 如果等待時發生中斷,在這種情況下取消尚未完成的任務 NullPointerException - 如果任務或其任意元素或 unit 為 null RejectedExecutionException - 如果所有任務都無法安排執行

 

public class CallableAndFutureTask {    /**     * @param args     */    public static class MyCallable implements Callable<String>{                private String name;        private int age;                public MyCallable(String name, int age) {            // TODO Auto-generated constructor stub            this.name = name;            this.age = age;        }        @Override        public String call() throws Exception {            // TODO Auto-generated method stub            Thread.sleep(new Random().nextInt(4000));            return "name:"+this.name+" "+"age:"+this.age;        }            }        public static void main(String[] args) {        //callable 執行任務,future得到任務執行結果        ExecutorService threadPool =  Executors.newFixedThreadPool(3);        int i = 10;        while(i-- > 0){        //建立一個tasks的list            List<MyCallable> tasks = new ArrayList<MyCallable>();            tasks.add(new MyCallable("tom", 20));            tasks.add(new MyCallable("john", 30));            tasks.add(new MyCallable("jack", 40));
       //用來接收任務執行結果 List
<Future<String>> taskResult = null; List<String> result = new ArrayList<String>(); System.out.println("等待結果:"+i); Long s = System.currentTimeMillis(); try { taskResult = threadPool.invokeAll(tasks, 3000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int j = 0; j < 3; j ++){ try { result.add(taskResult.get(j).get()); } catch (CancellationException e) { // TODO Auto-generated catch block// e.printStackTrace(); System.out.println(j+"cancled"); }catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("執行時間:"+(System.currentTimeMillis()-s)/1000); if(result.size() == 0){ System.out.println("get no data"); }else{ System.out.println(result); } } }}

和簡單的future callable比較,ExecutorService 的submit方法中不能設定時限,只能使用future.get(time,timeUint),但這樣一來,再接收結果時就變成了串列,即接收每個任務的結果都需要time的時間,三個任務的執行就變成了3*time,對於單個任務設定逾時可以使用這種方式

package com.newTechnologyInJava5;import java.util.ArrayList;import java.util.List;import java.util.Random;import java.util.concurrent.Callable;import java.util.concurrent.CancellationException;import java.util.concurrent.CompletionService;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorCompletionService;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.FutureTask;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;public class CallableAndFutureTask {    /**     * @param args     */    public static class MyCallable implements Callable<String>{                private String name;        private int age;                public MyCallable(String name, int age) {            // TODO Auto-generated constructor stub            this.name = name;            this.age = age;        }        @Override        public String call() throws Exception {            // TODO Auto-generated method stub            Thread.sleep(new Random().nextInt(4000));            return "name:"+this.name+" "+"age:"+this.age;        }            }        public static void main(String[] args) {        //callable 執行任務,future得到任務執行結果        ExecutorService threadPool =  Executors.newFixedThreadPool(3);        int i = 10;        while(i-- > 0){            Future<String> future1 = threadPool.submit(new MyCallable("tom", 20));            Future<String> future2 = threadPool.submit(new MyCallable("john", 30));            Future<String> future3 = threadPool.submit(new MyCallable("jack", 40));            try {                                try {                    result.add(future1.get(3000, TimeUnit.MILLISECONDS));                                    } catch (TimeoutException e) {                    // TODO Auto-generated catch block                    future1.cancel(true);                }                try {                    result.add(future2.get(3000, TimeUnit.MILLISECONDS));                                    } catch (TimeoutException e) {                    // TODO Auto-generated catch block                    future2.cancel(true);                }                try {                    result.add(future3.get(3000, TimeUnit.MILLISECONDS));                                    } catch (TimeoutException e) {                    // TODO Auto-generated catch block                    future3.cancel(true);                }                                } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            } catch (ExecutionException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            if(result.size() == 0){                System.out.println("get no data");            }else{                System.out.println(result);            }                    }    }}

 

java多線程批量執行的時限問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.