java多线程

Java 多线程(七):Executor 线程池框架

2018-03-12  本文已影响70人  聪明的奇瑞
类名 描述
Executor 线程池接口
ExecutorService 在基础 Executor 线程池接口上生命了生命周期管理方法、任务执行状况跟踪方法
ScheduledExecutorService 一个定时调度任务的接口
ScheduledThreadPoolExecutor ScheduledExecutorService 的实现,实现了可定时调度任务的线程池
ThreadPoolExecutor 线程池,可以通过调用 Executors 以下静态工厂方法来创建线程池并返回一个 ExecutorService 对象

ThreadPoolExecutor 构造函数

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue,
                          ThreadFactory threadFactory,
                          RejectedExecutionHandler handler) //后两个参数为可选参数

Executors

newFixedThreadPool

方法定义

//使用一个基于FIFO排序的阻塞队列,在所有corePoolSize线程都忙时新任务将在队列中等待
public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

使用例子

public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        IntStream.range(0, 6).forEach(i -> executorService.execute(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
                String threadName = Thread.currentThread().getName();
                System.out.println("finished: " + threadName);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }));
    }
}

//输出结果为:
//finished: pool-1-thread-1
//finished: pool-1-thread-2
//finished: pool-1-thread-3
//finished: pool-1-thread-4
//finished: pool-1-thread-5
//finished: pool-1-thread-1

newSingleThreadExecutor

方法定义

public static ExecutorService newSingleThreadExecutor(ThreadFactory threadFactory) {
    //corePoolSize和maximumPoolSize都等于,表示固定线程池大小为1
    return new FinalizableDelegatedExecutorService
        (new ThreadPoolExecutor(1, 1,
                                0L, TimeUnit.MILLISECONDS,
                                new LinkedBlockingQueue<Runnable>(),
                                threadFactory));
}

使用例子

public class Main {
    private static int num = 100;

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        IntStream.range(0, 100).forEach(i -> executorService.execute(() -> {
            String runnableName = "Runnable"+i+":";
            System.out.println(runnableName + num--);
        }));
        try {
            executorService.shutdown();
            executorService.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (!executorService.isTerminated()) {
                executorService.shutdownNow();
            }
        }
        System.out.println("执行结束");
    }
}

/** 输出结果为:
    Runnable0:100
    Runnable1:99
    Runnable2:98
    .....
    Runnable98:2
    Runnable99:1
    执行结束
**/

newScheduledThreadPool

方法定义

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

使用例子

public class Main {
    public static void main(String[] args) {
        ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
        IntStream.range(0, 2).forEach(i -> executorService.scheduleAtFixedRate(() -> {
                String threadName = Thread.currentThread().getName();
                System.out.println("finished: " + threadName);
        },1000, 2000, TimeUnit.MILLISECONDS));
    }
}

//输出结果为:
//finished: pool-1-thread-1
//finished: pool-1-thread-2
//finished: pool-1-thread-1
//finished: pool-1-thread-2
//finished: pool-1-thread-2
//finished: pool-1-thread-1

newCachedThreadPool

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}
public class Main {
    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        IntStream.range(0, 6).forEach(i -> executorService.execute(() -> {
                String threadName = Thread.currentThread().getName();
                System.out.println("finished: " + threadName);
        }));
    }
}

//输出结果为:
//finished: pool-1-thread-1
//finished: pool-1-thread-2
//finished: pool-1-thread-2
//finished: pool-1-thread-2
//finished: pool-1-thread-2
//finished: pool-1-thread-2
//线程池会缓存线程,尽可能的利用线程资源

ExecutorService 常用方法

上一篇 下一篇

猜你喜欢

热点阅读