您的位置:首页 > 其它

Multi-Programming-5 Thread Pools

2017-06-04 15:55 471 查看

1. 什么是线程池?

这里有官方JLS关于线程池的解释。

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 Thread pool represents a group of worker threads that are waiting for the job and reuse many times.

In case of thread pool, a group of fixed size threads are created. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

即:Java线程池代表的是一组工作线程,它们等待任务提交,并可以多次重复使用!

2. 为什么要使用线程池?

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.

Better performance It saves time because there is no need to create new thread.

简言之:线程池可以减少新建线程对象和清除线程对象的时间开销。

3. 一些常见线程池类

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. An important advantage of the fixed thread pool is that applications using it degrade gracefully.

newFixedThreadPool(): create an executor with fixed thread pool. 只允许给定数量的线程同时运行。

newCachedThreadPool(): create an executor with expanded thread pool. 同时可运行的线程数量可变,一般用于很多短时任务。

newSingleThreadExecutor(): create an executor that execute a single thread at a time. 单线程执行。

4. 线程池使用实例

package com.fqyuan._3threadPool;

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

public class ThreadPool {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(3);
for (int i = 0; i < 5; i++)
executor.submit(new Task(i));
System.out.println("All tasks submited.");
executor.shutdown();
try {
executor.awaitTermination(3, TimeUnit.SECONDS);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("All tasks shutdown.");
}
}

class Task implements Runnable {
private int id;

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

@Override
public void run() {
System.out.println(this.id + " starting");
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.id + " ends");
}

}


1 starting
0 starting
2 starting
All tasks submited.
1 ends
3 starting
0 ends
4 starting
2 ends
3 ends
4 ends
All tasks shutdown.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息