ExecutorCompletionService

package com.jdk.api;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

public class TestExecutorCompletionService {
public static void main(String[] args) throws Exception{
new TestExecutorCompletionService().TestExecutorCompletionService();
}

  public void TestExecutorCompletionService() throws Exception { 
        Executor defaultExecutor = Executors.newFixedThreadPool(10); 
        BlockingQueue queuePool = new ArrayBlockingQueue(8); 
        ; 
        ExecutorCompletionService ecs = new ExecutorCompletionService( 
                defaultExecutor, queuePool); 
        List<Future> futures = new ArrayList<Future>(); 
        futures.add(ecs.submit(new SyncCheckTask("1111"))); 
        futures.add(ecs.submit(new SyncCheckTask("2222"))); 
        futures.add(ecs.submit(new SyncCheckTask("3333"))); 
        futures.add(ecs.submit(new SyncCheckTask("4444"))); 
        futures.add(ecs.submit(new SyncCheckTask("5555"))); 
        futures.add(ecs.submit(new SyncCheckTask("6666"))); 
        futures.add(ecs.submit(new SyncCheckTask("66669"))); 
        int i = 0; 
        while (i <
        Future futrure = ecs.take(); 
            //Future futrure = ecs.poll(3000, TimeUnit.MILLISECONDS); 
            Object result = null == futrure ? null : futrure.get(); 
            System.out.println(result); 
            i++; 
        } 
       
       
    } 
    } 
class SyncCheckTask implements Callable<String> { 
    String ss = null; 
    public SyncCheckTask(String ss) { 
        this.ss = ss; 
    } 
    public String call() throws Exception { 
        Thread.sleep(Integer.parseInt(ss)); 
        return ss; 
    } 


}

你可能感兴趣的:(jdk-api)