在花了很多时间讨论线程池概念之后,通过阅读不同数量的博客代码并在Stackoverflow.com上发布问题,现在我对这个概念有了清晰的认识。但是与此同时,我在代码中发现了一些疑问。
当pool.assign(new TestWorkerThread())
; 在TestThreadPool
类中执行,它调用 done.workerBegin()
;。Done Class
中的方法,在此方法中_activeThreads
变量递增。但是我认为,从逻辑上讲,这是不正确的,因为如果线程数(在这种情况下为2)少于任务数(在TestThreadPool类中给出)(在这种情况下为5),则它会增加_activeThreads
(即_activeThreads = 5)
)不必要的计数。
Done类中有什么_started变量?
如何waitDone()和waitBegin() (在做类)执行其运作?(最好是逐步介绍这两种方法。)
代码如下。我正在根据其流程排列代码。
TestThreadPool类:
package hitesh;
/**
*
* @author jhamb
*/
public class TestThreadPool {
public static void main(String args[]) throws InterruptedException
{
ThreadPool pool = new ThreadPool(2);
for (int i = 1;i <= 5;i++) {
pool.assign(new TestWorkerThread());
}
System.out.println("All tasks are assigned");
pool.complete();
System.out.println("All tasks are done.");
}
}
TestWorkerThread类别:
package hitesh;
/**
*
* @author jhamb
*/
/**
* This class shows an example worker thread that can
* be used with the thread pool. It demonstrates the main
* points that should be included in any worker thread. Use
* this as a starting point for your own threads.
*/
public class TestWorkerThread implements Runnable {
static private int count = 0;
private int taskNumber;
protected Done done;
/**
*
* @param done
*/
TestWorkerThread()
{
count++;
taskNumber = count;
//System.out.println("tasknumber ---> " + taskNumber);
}
public void run()
{
System.out.println("TWT run starts --> " + this.toString());
for (int i=0;i <= 100;i += 25) {
System.out.println("Task number: " + taskNumber +
",percent complete = " + i );
try {
Thread.sleep((int)(Math.random()*500));
} catch (InterruptedException e) {
}
}
System.out.println("task for thread --> " + this.toString() + " completed");
}
}
ThreadPool类:-
package hitesh;
/**
*
* @author jhamb
*/
import java.util.*;
/*
* This is the main class for the thread pool. You should
* create an instance of this class and assign tasks to it.
*/
public class ThreadPool {
protected Thread threads[] = null;
Collection assignments = new ArrayList(3);
protected Done done = new Done();
public ThreadPool(int size) throws InterruptedException
{
threads = new WorkerThread[size];
for (int i=0;i<threads.length;i++) {
threads[i] = new WorkerThread(this);
threads[i].start();
System.out.println ("thread " + i + " started");
threads[i].sleep(1000);
}
}
public synchronized void assign(Runnable r)
{
done.workerBegin();
assignments.add(r);
System.out.println("Collection size ---> " + assignments.size() + " Thread can work on this");
notify();
}
public synchronized Runnable getAssignment()
{
try {
while ( !assignments.iterator().hasNext() )
wait();
Runnable r = (Runnable)assignments.iterator().next();
assignments.remove(r);
return r;
} catch (InterruptedException e) {
done.workerEnd();
return null;
}
}
public void complete()
{
done.waitBegin();
done.waitDone();
}
}
WorkerThread类别:
package hitesh;
import java.util.*;
/**
*
* @author jhamb
*/
/**
* The worker threads that make up the thread pool.
*/
class WorkerThread extends Thread {
/**
* True if this thread is currently processing.
*/
public boolean busy;
/**
* The thread pool that this object belongs to.
*/
public ThreadPool owner;
/**
* The constructor.
*
* @param o the thread pool
*/
WorkerThread(ThreadPool o)
{
owner = o;
}
/**
* Scan for and execute tasks.
*/
//@Override
public void run()
{
System.out.println("Threads name : "+ this.getName() + " working.....");
Runnable target = null;
do {
System.out.println("enter in do while " + this.getName() );
target = owner.getAssignment();
System.out.println("GetAssignment k aage aa gya mai " + target);
if (target!=null) {
target.run();
//target.
owner.done.workerEnd();
}
} while (target!=null);
System.out.println("do while finishes for "+ this.getName());
}
}
完成课程:
package hitesh;
/**
*
* @author jhamb
*/
/**
*
* This is a thread pool for Java, it is
* simple to use and gets the job done. This program and
* all supporting files are distributed under the Limited
* GNU Public License (LGPL, http://www.gnu.org).
*
* This is a very simple object that
* allows the TheadPool to determine when
* it is done. This object implements
* a simple lock that the ThreadPool class
* can wait on to determine completion.
* Done is defined as the ThreadPool having
* no more work to complete.
*
* Copyright 2001 by Jeff Heaton
*
* @author Jeff Heaton (http://www.jeffheaton.com)
* @version 1.0
*/
public class Done {
/**
* The number of Worker object
* threads that are currently working
* on something.
*/
private int _activeThreads = 0;
/**
* This boolean keeps track of if
* the very first thread has started
* or not. This prevents this object
* from falsely reporting that the ThreadPool
* is done, just because the first thread
* has not yet started.
*/
private boolean _started = false;
/**
* This method can be called to block
* the current thread until the ThreadPool
* is done.
*/
synchronized public void waitDone()
{
try {
while ( _activeThreads>0 ) {
wait();
}
} catch ( InterruptedException e ) {
}
}
/**
* Called to wait for the first thread to
* start. Once this method returns the
* process has begun.
*/
synchronized public void waitBegin()
{
try {
while ( !_started ) {
wait();
}
} catch ( InterruptedException e ) {
}
}
/**
* Called by a Worker object
* to indicate that it has begun
* working on a workload.
*/
synchronized public void workerBegin()
{
_activeThreads++;
_started = true;
notify();
}
/**
* Called by a Worker object to
* indicate that it has completed a
* workload.
*/
synchronized public void workerEnd()
{
_activeThreads--;
notify();
}
/**
* Called to reset this object to
* its initial state.
*/
synchronized public void reset()
{
_activeThreads = 0;
}
}
请帮忙。提前致谢。寻找您的友好回应。
现在,我非常清楚地了解了整个代码。如果您对这段代码有任何疑问,可以提出疑问。
在阅读了大量有关此内容后,我的问题的答案如下。
是的,你是对的,这在逻辑上是错误的。最好是_activeTasks。当线程池没有更多工作时,它用于杀死所有线程,因为waitDone()函数仅在_activeTasks <= 0时成功执行。
在waitBegin()方法中使用此变量。每当任何任务启动时,它更新由_started TRUE,意味着由用户指定的任务正处于由线程处理,手段线程开始执行这些任务的工作。如果用户未提供任务,则所有线程仍处于活动状态,并正在等待任务。这是此变量的使用。
当线程开始处理任务时,waitBegin()方法成功执行,因为在这种情况下,只有_started才为true。否则,线程将继续等待某些任务。waitDone()仅在_activeTasks变为零时才成功执行,因为这是线程池没有任何要执行的工作的唯一情况,这意味着线程池完成了其工作。否则,它将一直等待直到所有任务完成,这意味着它将等到_activeTasks变为零
本文向大家介绍用python实现的线程池实例代码,包括了用python实现的线程池实例代码的使用技巧和注意事项,需要的朋友参考一下 python3标准库里自带线程池ThreadPoolExecutor和进程池ProcessPoolExecutor。 如果你用的是python2,那可以下载一个模块,叫threadpool,这是线程池。对于进程池可以使用python自带的multiprocessing
本文向大家介绍Python实现线程池代码分享,包括了Python实现线程池代码分享的使用技巧和注意事项,需要的朋友参考一下 原理:建立一个任务队列,然多个线程都从这个任务队列中取出任务然后执行,当然任务队列要加锁,详细请看代码
本文向大家介绍实例代码讲解Python 线程池,包括了实例代码讲解Python 线程池的使用技巧和注意事项,需要的朋友参考一下 大家都知道当任务过多,任务量过大时如果想提高效率的一个最简单的方法就是用多线程去处理,比如爬取上万个网页中的特定数据,以及将爬取数据和清洗数据的工作交给不同的线程去处理,也就是生产者消费者模式,都是典型的多线程使用场景。 那是不是意味着线程数量越多,程序的执行效率就越快呢
出于学习的目的,我正在尝试用java实现自己的线程池。下面是我已经实现的。我对这个实现有几个问题: > 虽然我像内置java一样使用BlockingQueue执行器希望我们提供Runnable对象(通过执行方法)。但在我的情况下,我觉得我可以创建任何对象而不是Runnable。那么为什么Java执行器期望Runnable,我尝试查看源代码,但还不能弄清楚。 这个原始实现还有什么问题吗? 请找到密码
本文向大家介绍java 线程池的实现方法,包括了java 线程池的实现方法的使用技巧和注意事项,需要的朋友参考一下 线程池有以下几种实现方式: Executors目前提供了5种不同的线程池创建配置: 1、newCachedThreadPool() 它是用来处理大量短时间工作任务的线程池,具有几个鲜明特点:它会试图缓存线程并重用,当无缓存线程可用时,就会创建新的工作线程;如果线程闲置时间超过60秒,
本文向大家介绍python实现线程池的方法,包括了python实现线程池的方法的使用技巧和注意事项,需要的朋友参考一下 本文实例讲述了python实现线程池的方法。分享给大家供大家参考。具体如下: 原理:建立一个任务队列,然多个线程都从这个任务队列中取出任务然后执行,当然任务队列要加锁,详细请看代码 文件名:thrd_pool.py 系统环境:ubuntu linux & python2.6 执行