线程池,给予其任务执行,线程池本身又有线程的概念,所以现在就有三个实体,1个线程池,m个线程,n个任务,看程序:
import java.util.LinkedList;
/**
A thread pool is a group of a limited number of threads that
are used to execute tasks.
*/
public class ThreadPool extends ThreadGroup {
private boolean isAlive;
private LinkedList taskQueue;
private int threadID;
private static int threadPoolID;
/**
Creates a new ThreadPool.
@param numThreads The number of threads in the pool.
*/
public ThreadPool(int numThreads) {
super("ThreadPool-" + (threadPoolID++));
setDaemon(true);
isAlive = true;
taskQueue = new LinkedList();
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
}
/**
Requests a new task to run. This method returns
immediately, and the task executes on the next available
idle thread in this ThreadPool.
<p>Tasks start execution in the order they are received.
@param task The task to run. If null, no action is taken.
@throws IllegalStateException if this ThreadPool is
already closed.
*/
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask()
throws InterruptedException {
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
}
/**
Closes this ThreadPool and returns immediately. All
threads are stopped, and any waiting tasks are not
executed. Once a ThreadPool is closed, no more tasks can
be run on this ThreadPool.
*/
public synchronized void close() {
if (isAlive) {
isAlive = false;
taskQueue.clear();
interrupt();
}
}
/**
Closes this ThreadPool and waits for all running threads
to finish. Any waiting tasks are executed.
*/
public void join() {
// notify all waiting threads that this ThreadPool is no
// longer alive
synchronized (this) {
isAlive = false;
notifyAll();
}
// wait for all threads to finish
Thread[] threads = new Thread[activeCount()];
int count = enumerate(threads);
for (int i=0; i<count; i++) {
try {
threads[i].join();
}
catch (InterruptedException ex) { }
}
}
/**
A PooledThread is a Thread in a ThreadPool group,
designed to run tasks (Runnables).
*/
private class PooledThread extends Thread {
public PooledThread() {
super(ThreadPool.this,
"PooledThread-" + (threadID++));
}
public void run() {
while (!isInterrupted()) {
// get a task to run
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
// if getTask() returned null or was interrupted,
// close this thread by returning.
if (task == null) {
return;
}
// run the task, and eat any exceptions it throws
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
}
}
}
public class ThreadPoolTest {
public static void main(String[] args) {
if (args.length != 2) {
System.out.println("Tests the ThreadPool task.");
System.out.println(
"Usage: java ThreadPoolTest numTasks numThreads");
System.out.println(
" numTasks - integer: number of task to run.");
System.out.println(
" numThreads - integer: number of threads " +
"in the thread pool.");
return;
}
int numTasks = Integer.parseInt(args[0]);
int numThreads = Integer.parseInt(args[1]);
// create the thread pool
ThreadPool threadPool = new ThreadPool(numThreads);
// run example tasks
for (int i=0; i<numTasks; i++) {
threadPool.runTask(createTask(i));
}
// close the pool and wait for all tasks to finish.
threadPool.join();
}
/**
Creates a simple Runnable that prints an ID, waits 500
milliseconds, then prints the ID again.
*/
private static Runnable createTask(final int taskID) {
return new Runnable() {
public void run() {
System.out.println("Task " + taskID + ": start");
// simulate a long-running task
try {
Thread.sleep(500);
}
catch (InterruptedException ex) { }
System.out.println("Task " + taskID + ": end");
}
};
}
}
总体流程如下:
1. 创建一个带m个线程的线程池
// create the thread pool
ThreadPool threadPool = new ThreadPool(numThreads);
注意新建线程池的时候,其内部线程就已经启动了
for (int i=0; i<numThreads; i++) {
new PooledThread().start();
}
每个线程的工作类似,都是获取任务并执行任务内容,但任务未分配到位,就进行阻塞,到位一个任务就得到一个任务并执行之
public synchronized void runTask(Runnable task) {
if (!isAlive) {
throw new IllegalStateException();
}
if (task != null) {
taskQueue.add(task);
notify();
}
}
protected synchronized Runnable getTask()
throws InterruptedException {
while (taskQueue.size() == 0) {
if (!isAlive) {
return null;
}
wait();
}
return (Runnable)taskQueue.removeFirst();
}
到这里也许会想,非要分配一个任务,获取一个任务再执行一个任务这种工作模式吗,我就不能一下分配所有任务后,一下获取,然后全部执行吗?我想可以肯定是可以的,但无论哪种方式,都必须解决一个有序获取任务的问题,否则造成n个线程争一个任务就不太好了,而现在等待的线程中会随机取一个线程分配其任务,就避免了无序争抢的问题
2. 给线程池分配n个任务
// run example tasks
for (int i=0; i<numTasks; i++) {
threadPool.runTask(createTask(i));
}
值得一提的是,既然是分配任务,这里为什么要写成runTask方法名呢,原因在于之前那些工作线程都已经启动了,只是因为没有任务而都被阻塞着,只要任务分配到位就会继续工作,因此在这里分配任务也就意味着启动了执行任务的开关,因此命名为runTask也是顺理成章的~
分享到:
相关推荐
通过设定线程池大小,可以限制并发执行的任务数量,避免资源过度消耗。 `FutureTask`是线程池处理任务的一种方式,它不仅包含了一个`Runnable`或`Callable`任务,还提供了检查任务是否完成、获取结果、取消任务等...
线程池的工作原理是通过维护一个工作线程集合,当提交任务时,线程池会从队列中选择一个空闲线程来执行任务,而不是每次都创建新的线程。这样可以避免频繁的线程创建和销毁带来的开销。线程池可以通过设置核心线程数...
线程池是一种多线程执行的管理机制,它预先创建了一组可重用的线程,而不是每次需要执行任务时都新建线程。线程池可以有效地减少线程创建和销毁的开销,提高系统的响应速度和并发性能。Java中的`java.util....
线程池是一种多线程处理形式,预先创建了多个线程,当需要执行任务时,直接从线程池中取出一个线程来执行任务,而不是每次都创建新的线程。在Android中,我们经常使用`ExecutorService`和`ThreadPoolExecutor`来实现...
`rust-threadpool` 库正是遵循了这种设计模式,它提供了 API 使得开发者可以方便地向线程池提交任务,从而实现高效的并行计算。 在 `rust-threadpool` 中,你可以通过以下方式使用线程池: 1. **创建线程池**:...
当需要执行任务时,从线程池中取出线程,而不是每次都创建新的线程。这样可以避免线程创建和销毁的开销,提高系统的响应速度和并发处理能力。特别是在多核处理器系统中,线程池能充分利用硬件资源,提升程序的运行...
【基于线程池的GPU任务并行计算模式研究】 随着GPU技术的发展,它已经成为一种具有高并发和高内存带宽的通用协处理器,广泛应用于数据处理和高性能计算领域。然而,由于GPU和CPU在体系结构和编程模型上的显著差异,...
在现代计算机科学中,多线程编程被广泛应用于并行处理和提高程序性能。然而,线程的创建和销毁是一个开销较大的...线程池模式适用于需要频繁执行大量短生命周期任务的场景,如服务器请求处理、并行计算和定时任务等。
- **任务提交**:当有新任务到来时,线程池会选择一个空闲的线程执行任务,而不是每次都创建新的线程。 - **任务执行**:线程从任务队列中取出任务并执行,完成后返回线程池等待下一个任务。 - **线程管理**:...
线程池由一组可重用的线程组成,当有新的任务需要执行时,线程池会从已创建的线程中选择一个空闲线程来执行任务,而不是每次都创建新的线程。任务完成后,线程不会立即销毁,而是返回线程池等待下一次任务。这样...
2. **任务队列**:线程池需要一个任务队列来存储待执行的任务。可以使用优先级队列、无锁数据结构等方法来提高并发效率。 3. **任务调度**:如何将任务分配给线程,这可能涉及负载均衡策略,如轮询、优先级调度等。 ...
当有新的任务到来时,线程池会从池中选择一个空闲线程执行任务,而不是每次都创建新线程。线程池能有效控制运行的线程数量,防止过多线程导致系统资源耗尽。 3. **线程池的工作流程**: - **任务提交**:客户端向...
线程池由一组工作线程组成,这些线程负责执行任务队列中的任务。当新的任务被提交到线程池时,如果当前有空闲线程,那么任务会被立即分配给一个线程;如果没有空闲线程,任务会被添加到等待队列中,等待线程池根据...
线程池是由一组预先创建的线程组成的,这些线程可以复用,而不是每次执行任务时都创建新的线程。`ThreadPoolExecutor`是Java并发包`java.util.concurrent`中的核心类,用于实现线程池服务。通过设置线程池参数,我们...
Java线程池是一种高效管理线程的技术,它允许开发者预定义一组线程,根据任务的需要灵活调度,而不是每次需要执行任务时都创建新的线程。这种设计模式大大提高了系统的性能,减少了系统资源的消耗,特别是在高并发...
如果有,就会立即执行任务;如果没有,任务会被放入一个任务队列等待。 - 当某个工作线程完成任务后,它会从队列中取出下一个任务继续执行,直到线程池关闭或者任务队列为空。 - 如果线程池的大小达到最大限制并且...
生产者将任务放入队列,消费者从队列中取出并执行任务。 - **有限容量策略**:线程池可以设定最大线程数量,当达到上限时,新增任务会被阻塞,直到线程池中有线程完成任务释放资源。 4. **C++线程池的实现细节** ...
线程池的使用可以有效地管理和控制并发执行的任务,减少线程创建和销毁的开销,提高系统资源利用率。 在描述中提到的博文链接虽然没有给出具体内容,但通常会包含线程池的工作原理、创建方式以及最佳实践等内容。...
线程池是一种高效的多线程编程模式,它通过预创建线程并复用这些线程来处理不断到来的任务,极大地提高了系统的响应速度和吞吐量。本文介绍的LINUX_c++线程池框架提供了高度灵活且易于扩展的基础架构,适用于各种...
如果有,那么就分配一个空闲线程去执行任务;如果没有,线程池可能会创建新的线程或者等待直到有线程完成其工作并返回到池中。这种机制避免了频繁地创建和销毁线程,减少了系统开销。 在VC++中,线程池通常通过...