java线程池

ExecutorService executor = Executors.newFixedThreadPool(10);

        executor.shutdown();
        executor.shutdownNow();
        Thread.currentThread().getName(); //获取线程名称
        //没有返回值
        executor.submit(new Runnable() {

            @Override
            public void run() {


            }
        });
        executor.execute(new Runnable() {

            @Override
            public void run() {


            }
        });

        Future submit = executor.submit(new Callable() {

            @Override
            public T call() throws Exception {

                return null;
            }
        }); // 有返回值
        submit.get(); //获取返回值
    }

executor.shutdown()
executor.shutdownnow()

package run;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import service.CrawlerPostgraduate;

public class Start {
    public static void main(String[] args) {
        // 初始化多个需要爬的类
        List> tasks = new ArrayList>();
        CrawlerPostgraduate cp = new CrawlerPostgraduate();
        tasks.add(cp);
        // 线程池
        ExecutorService executor = Executors.newFixedThreadPool(10);
        List> invokeAll = null;
        try {
            invokeAll = executor.invokeAll(tasks);
        } catch (InterruptedException e) {

            e.printStackTrace();
        }

        for (Future future : invokeAll) {
            try {
                System.out.println(future.get());
            } catch (InterruptedException e) {

                e.printStackTrace();
            } catch (ExecutionException e) {

                e.printStackTrace();
            }
        }
        executor.shutdown();
    }

}

你可能感兴趣的:(线程池)