1. 程式人生 > >Java使用線程池

Java使用線程池

executors ice mit checked i++ 函數 new test color

多線程主函數

package UnitTest;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@SuppressWarnings("unchecked")
public class test {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(10);
        List
<Future> resultList = new ArrayList<>(); for (int i = 1; i < 101; i++) { Future future = fixedThreadPool.submit(new ThreadWithRunnable(i)); resultList.add(future); } fixedThreadPool.shutdown(); fixedThreadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); System.out.println(
"所有進程成功結束!"); } }

小函數

package UnitTest;

import java.util.concurrent.Callable;

public class ThreadWithRunnable implements Callable {
    private int number;
    public ThreadWithRunnable(int number){
        this.number = number;
    }

    @Override
    public Object call() {
        System.out.println(
"開始線程:"+Thread.currentThread().getName()+" 傳入參數:"+number); return number; } }

Java使用線程池