Java 如何在线程池中编写run方法
通过阅读线程池,我感到非常困惑。我了解了这个概念,以及它们的实际工作原理。 但我在这一部分感到困惑,如何编写代码 我在网上搜索了很多。最后我得到了一个博客,上面有代码,如下所示 条件为,不使用内置类 代码1Java 如何在线程池中编写run方法,java,multithreading,threadpool,Java,Multithreading,Threadpool,通过阅读线程池,我感到非常困惑。我了解了这个概念,以及它们的实际工作原理。 但我在这一部分感到困惑,如何编写代码 我在网上搜索了很多。最后我得到了一个博客,上面有代码,如下所示 条件为,不使用内置类 代码1 public class ThreadPool { private BlockingQueue taskQueue = null; private List<PoolThread> threads = new ArrayList<PoolThread>();
public class ThreadPool {
private BlockingQueue taskQueue = null;
private List<PoolThread> threads = new ArrayList<PoolThread>();
private boolean isStopped = false;
public ThreadPool(int noOfThreads, int maxNoOfTasks){
taskQueue = new BlockingQueue(maxNoOfTasks);
for(int i=0; i<noOfThreads; i++){
threads.add(new PoolThread(taskQueue));
}
for(PoolThread thread : threads){
thread.start();
}
}
public void synchronized execute(Runnable task){
if(this.isStopped) throw
new IllegalStateException("ThreadPool is stopped");
this.taskQueue.enqueue(task);
}
public synchronized void stop(){
this.isStopped = true;
for(PoolThread thread : threads){
thread.stop();
}
}
}
代码3:-
public class BlockingQueue {
private List queue = new LinkedList();
private int limit = 10;
public BlockingQueue(int limit){
this.limit = limit;
}
public synchronized void enqueue(Object item)
throws InterruptedException {
while(this.queue.size() == this.limit) {
wait();
}
if(this.queue.size() == 0) {
notifyAll();
}
this.queue.add(item);
}
public synchronized Object dequeue()
throws InterruptedException{
while(this.queue.size() == 0){
wait();
}
if(this.queue.size() == this.limit){
notifyAll();
}
return this.queue.remove(0);
}
}
我试图理解,这段代码是做什么的。
但是我不知道这个代码的流程。你能帮我理解这个代码吗
Mainly I have problems in **Code 2 :- run method**
Why execute method's argument are of Runnable type?
How input array given to this code??
帮帮我
提前感谢。编辑:
我现在明白这是一个课堂项目,但我将把我的答案留给后代。
如果您试图在Java下使用线程池,那么所有这些都已经由Java.util.concurrent.*
类为您实现了。其他答案说明并解释您的具体代码
例如,这就是使用ExecutorService
代码设置线程池所需的。在封盖下面,ExecutorService
处理线程并使用LinkedBlockingQueue
。您可以定义MyJob
类,该类实现“Runnable”,并执行池中线程运行的工作。根据您的需要,它可以是短期任务,也可以是长期任务
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// define your jobs somehow
for (MyJob job : jobsToDo) {
threadPool.submit(job);
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
public class MyJob implements Runnable {
// you can construct your jobs and pass in context for them if necessary
public MyJob(String someContext) {
...
}
public void run() {
// process the job
}
}
编辑:
我现在明白这是一个课堂项目,但我将把我的答案留给后代。
如果您试图在Java下使用线程池,那么所有这些都已经由Java.util.concurrent.*
类为您实现了。其他答案说明并解释您的具体代码
例如,这就是使用ExecutorService
代码设置线程池所需的。在封盖下面,ExecutorService
处理线程并使用LinkedBlockingQueue
。您可以定义MyJob
类,该类实现“Runnable”,并执行池中线程运行的工作。根据您的需要,它可以是短期任务,也可以是长期任务
// create a thread pool with 10 workers
ExecutorService threadPool = Executors.newFixedThreadPool(10);
// or you can create an open-ended thread pool
// ExecutorService threadPool = Executors.newCachedThreadPool();
// define your jobs somehow
for (MyJob job : jobsToDo) {
threadPool.submit(job);
}
// once we have submitted all jobs to the thread pool, it should be shutdown
threadPool.shutdown();
...
public class MyJob implements Runnable {
// you can construct your jobs and pass in context for them if necessary
public MyJob(String someContext) {
...
}
public void run() {
// process the job
}
}
循环,直到线程池停止
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
将头任务从任务队列中拉出
runnable.run();
运行任务
} catch(Exception e){
//log or otherwise report exception,
//but keep pool thread alive.
如果任务抛出异常,请不要执行任何特殊操作,只是不要传递异常
}
}
}
循环,直到线程池停止
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
将头任务从任务队列中拉出
runnable.run();
运行任务
} catch(Exception e){
//log or otherwise report exception,
//but keep pool thread alive.
如果任务抛出异常,请不要执行任何特殊操作,只是不要传递异常
}
}
}
为什么必须编写自己的线程池?使用Executors.*ThreadPool()方法创建线程池,然后使用submit(*)方法提交可调用或可运行的线程池。@allprog:我编写了这段代码,这段代码很容易构建。但是我的老师要求不使用内置类来构建这个。这就是我发布这篇文章的原因。很好,你让社区检查家庭作业。:)不幸的是,做正确的服务是困难的。如果您提供带有取消的异步未来接口,那么您必须非常小心。您应该查看JDK源代码以获得正确的实现。它将比您现在拥有的要复杂得多。@allprog:不,我不是让社区来检查代码的。我花了很多时间研究这个问题,最后我在小模块中遇到了问题,然后我问了这个答案。我会考虑你的建议。谢谢:)别客气。问总比不知道答案好。:)您也应该对BlockingQueue使用泛型,但在任何情况下都不要对enqueue和dequeue使用对象类型。它会毁了你的密码!JDK中有一个同名的功能实现,您不能使用它吗?我认为ExecutorService(正确实现)已经比简单的家庭作业或任务复杂得多了。为什么您必须编写自己的线程池?使用Executors.*ThreadPool()方法创建线程池,然后使用submit(*)方法提交可调用或可运行的线程池。@allprog:我编写了这段代码,这段代码很容易构建。但是我的老师要求不使用内置类来构建这个。这就是我发布这篇文章的原因。很好,你让社区检查家庭作业。:)不幸的是,做正确的服务是困难的。如果您提供带有取消的异步未来接口,那么您必须非常小心。您应该查看JDK源代码以获得正确的实现。它将比您现在拥有的要复杂得多。@allprog:不,我不是让社区来检查代码的。我花了很多时间研究这个问题,最后我在小模块中遇到了问题,然后我问了这个答案。我会考虑你的建议。谢谢:)别客气。问总比不知道答案好。:)您也应该对BlockingQueue使用泛型,但在任何情况下都不要对enqueue和dequeue使用对象类型。它会毁了你的密码!JDK中有一个同名的功能实现,您不能使用它吗?我认为ExecutorService(正确实现)已经比简单的家庭作业或工作分配复杂得多了。`public PoolThread(BlockingQueue){taskQueue=queue;}`据我所知,这些行可以将taskQueue的副本提供给所有线程工作者。我说得对吗?再告诉我一件事,我们如何给代码1指定inut数组。因为要开始,我们必须调用代码1的execute方法。@FreakyCheeky:第一个问题:是的。每个线程获得对同一队列的引用。第二个问题:调用execute函数,它将任务放在共享队列中。告诉我一件事,为什么execute ethod参数是可运行类型??我不明白这一点。这在我们的文档中有解释。它正是为了这个目的而设计的。`public PoolThread(BlockingQueue){taskQueue=queue;}`据我所知,这些行用于将taskQueue的副本提供给所有线程工作者。我说得对吗?