Multi-Programming-5 Thread Pools

1.What is Thread Pools?

点击获取官方解释����

Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.
在java.util.concurrent包中,大部分的executor实现使用到了线程池。 这种线程和它所执行的Runnable/Callable的任务相分离,并通常用于执行多个任务。

2.Why using thread pools?

Using worker threads minimizes the overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.
在线程创建时的花销很大,在大规模应用中,分配和回收线程对象将会产生巨大的内存管理开支。

3. Common type of thread pools

    One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Tasks are submitted to the pool via an internal queue, which holds extra tasks whenever there are more active tasks than threads.
    The newCachedThreadPool method creates an executor with an expandable thread pool. This executor is suitable for applications that launch many short-lived tasks.
    The newSingleThreadExecutor method creates an executor that executes a single task at a time.
    Several factory methods are ScheduledExecutorService versions of the above executors.
常见的线程池产生方法有:
newFixedThreadPool():只允许给定数量的线程同时运行。
newCachedThreadPool():同时可运行线程数量可变,通常用于很多短时任务。
newSingleThreadExecutor():单线程执行。

4.Examples…

代码:
package com.fqyuan.blog;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class ThreadPoolDemo {
    public static void main(String[] args) {
        ThreadPoolDemoUtil.demonstrate();
    }
}

class ThreadPoolDemoUtil {
    public static void demonstrate() {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        for (int i = 0; i < 6; i++) {
            executor.submit(new Task(i));
        }
        System.out.println("All tasks submited.");
        executor.shutdown();
        try {
            executor.awaitTermination(1, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("All tasks finished.");
    }
}

class Task implements Runnable {
    private int id;

    public Task(int id) {
        this.id = id;
    }

    @Override
    public void run() {
        System.out.println(id + " Starting.");
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(id + " Ending.");
    }
}
运行结果:
All tasks submited.
2 Starting.
0 Starting.
1 Starting.
2 Ending.
1 Ending.
0 Ending.
4 Starting.
3 Starting.
5 Starting.
4 Ending.
5 Ending.
3 Ending.
All tasks finished.

相关代码笔记,@GitHub

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