package com.niewj.thread;  
  
import java.util.HashSet;  
import java.util.List;  
import java.util.Set;  
import java.util.concurrent.*;  
  
public class ThreadTest {  
  
    /** 
     * 同一个map里面存储了各个水果的数量, 
     * 
     * @param args 
     */  
    public static void main(String[] args) throws ExecutionException, InterruptedException {  
  
        /** 
         * invokeAny 3个线程中最快的那个会返回,但是其他的也可能都执行完/也可能不执行; 
         */  
        testInvokeAny();   
    }  
  
    private static void testInvokeAny() throws ExecutionException, InterruptedException {  
        ExecutorService executorService = Executors.newSingleThreadExecutor();  
  
        Set<Callable<String>> tskSet = new HashSet<>();  
  
        tskSet.add(new Callable<String>() {  
            public String call() throws Exception {  
                System.out.println("Task 1 ..........running.......");  
                return "Task 1";  
            }  
        });  
        tskSet.add(new Callable<String>() {  
            public String call() throws Exception {  
                System.out.println("Task 2 ..........running.......");  
                return "Task 2";  
            }  
        });  
        tskSet.add(new Callable<String>() {  
            public String call() throws Exception {  
                System.out.println("Task 3 ..........running.......");  
                return "Task 3";  
            }  
        });  
  
        String result = executorService.invokeAny(tskSet);  
  
        System.out.println("result = " + result);  
  
        executorService.shutdown();  
    }  
  
}  

invokeAny 3个线程中最快的那个会返回,

但: 其他的2个也可能都执行完/也可能不执行;

---[2018-08-23]---


丰木
322 声望19 粉丝

遇见超乎想象的自己!