【发布时间】:2018-05-29 11:05:41
【问题描述】:
我知道不应调用 run 方法来启动新线程执行,但我指的是this article,他们在另一个 run 方法中调用了runnable.run();,这似乎暗示它启动了一个新线程或它根本没有创建线程,它只是创建一个新线程并在同一个线程中运行所有可运行的,即逐个任务?
这里是文章提到的代码。
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 synchronized void execute(Runnable task) throws Exception{
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.doStop();
}
}
}
和
public class PoolThread extends Thread {
private BlockingQueue taskQueue = null;
private boolean isStopped = false;
public PoolThread(BlockingQueue queue){
taskQueue = queue;
}
public void run(){
while(!isStopped()){
try{
Runnable runnable = (Runnable) taskQueue.dequeue();
runnable.run();
} catch(Exception e){
//log or otherwise report exception,
//but keep pool thread alive.
}
}
}
public synchronized void doStop(){
isStopped = true;
this.interrupt(); //break pool thread out of dequeue() call.
}
public synchronized boolean isStopped(){
return isStopped;
}
}
问题:
为什么 thread.start(); 在构造函数中被调用?
如果 thread.start(); 之前被调用,我该如何入队我的任务 调用 this.taskQueue.enqueue(task);
要了解所有这些,请为此示例发布一个驱动程序类 使用 maxNoOfTasks=10 和 noOfThreads=3。输出 同样将不胜感激。
- run 方法中的 Runnable.run() 是否会启动一个新线程?
谢谢
【问题讨论】:
-
run方法只是一个普通的方法,没什么特别的。Thread#start方法启动一个线程。之后它调用run。但是run本身只执行方法,与线程无关。Runnable不是线程,它只是有一个名为run的方法。
标签: java multithreading