Java 多线程传值demo

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
public class findProduct {


public static void main(String[] args) throws ExecutionException, InterruptedException {
    Map> map = new HashMap<>();
    long startTime=System.nanoTime();
    List>> futureList = new ArrayList<>();
    ExecutorService service = Executors.newFixedThreadPool(10);
    for(int i=0;i<1000;i++){
        futureList.add(service.submit(new Products(i,i*2)));
    }
    service.shutdown();


    while (true) {
        if (service.isTerminated()) {
            int m = 0;
            for (Future> future : futureList) {
                if (null != future.get()) {
                    m += 1;
                    List result = future.get();
                    map.put(m,result);
                }
            }
            break;
        }
        Thread.sleep(50);
    }


    long endTime=System.nanoTime(); //获取结束时间
    System.out.println("程序运行时间: "+(endTime-startTime)+"ns");
    System.out.println(map);
}


static class Products implements Callable>{
    private Integer key;
    private int value;


    public Products(Integer key, int value){
        this.key = key;
        this.value = value;
    }


    @Override
    public List call() throws Exception {
        List list = new ArrayList<>();
        if (key % 10 == 0){
            Thread.currentThread().sleep(100);
        }

        String product = "分片:" + key + "产品" + value;
        list.add(product);
        return list;
    }
}

}

你可能感兴趣的:(Java 多线程传值demo)