Threadpool 如何重用线程以及它是如何工作的 [英] How Threadpool re-use Threads and how it works

查看:24
本文介绍了Threadpool 如何重用线程以及它是如何工作的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的多线程概念很弱,正在努力学习.

My multithreading concepts are weak and trying to learn.

据我所知,在 Java 中,我们不能多次调用一个线程:

In Java what I know is, we can't call a thread more than once:

Thread t = new Thread; //Some Runnable
t.start();

t.start(); //Illegal and throw Exception at runtime.

据我所知,当你再次调用 t.start() 时它会抛出异常,因为一旦它退出 run() 线程的关联堆栈就会被销毁code> 方法,您正在尝试再次初始化.

As far as I know, it throws exception when you call t.start() again because the associated stack for the thread is destroyed once it goes out of run() method and you are trying to initialize things again.

在那种情况下,我对线程池的了解是,它提供了更好的性能&节省时间,因为无需创建新线程(我在 this 中阅读).

In that case, what I know about thread pool is, it gives better performance & saves time because there is no need to create new thread (I read in this).

如果在线程池场景中不需要创建新线程,那么它如何与刚刚完成run方法的同一个线程一起工作,该线程是否可以再次使用?

If there is no need to create new thread in thread pool scenario, then how it works with same thread which just finished its run method, will that thread can be used again?

我阅读了this,它说java.util.concurrent 中的 executor 实现大多使用线程池,由工作线程组成.这种线程与其执行的 Runnable 和 Callable 任务分开存在,通常用于执行多个任务."

那么这里的 Worker 线程是什么,它和普通的 Java 线程有什么不同吗?

So what is Worker thread here, is it something different then normal Java threads?

通过这个链接,我得到了一些东西但是仍然不明白当我们使用线程池时可以消除什么样的东西以及为什么它比使用普通的java线程提供更好的性能.

With this link, I got something but still confused on what kind of stuff can be eliminated when we use thread pool and why it gives better performance than using normal java threads.

所以我们可以这样说吗,

So can we say like this,

线程分为三个部分,

  1. 创建(告诉操作系统这是新线程,为其创建堆栈.)
  2. 使用 run() 方法执行 Runnable.
  3. 销毁线程.

因此,考虑到以上 3 个步骤,在创建固定数量的线程后,可以消除线程池中的第 1 步和第 3 步.每个任务只会执行第 2 步,这就是线程池更快的原因?我们可以这样说吗?我说得对吗?

So, considering above 3 steps, With thread pool step 1 and step 3 can be eliminated after fixed number of thread creation. Only step 2 for each task will be executed that is why threadpool is faster? Can we say like this? Am I correct?

推荐答案

如果在ThreadPool场景中不需要创建新的Thread,那么它如何与刚刚完成run方法的同一个线程一起工作,那个线程可以再次使用吗?

If there is no need to create new Thread in ThreadPool scenario, then how it works with same thread which just finished its run method, will that Thread can be used again?

简单 - 原始线程从未真正完成.它只是等待另一个任务执行.在伪代码中:

Simple - the original thread never actually completes. It just waits for another task to execute. In pseudo-code:

// No, this isn't even slightly accurate! General impression only :)
while (!pool.isShutdown()) {
    Runnable task = pool.waitForTaskOnQueue();
    task.run();
}

(显然,当线程池关闭时,它也需要停止等待线程等待另一个任务 - 但希望您能大致了解.)

(Obviously when a thread pool is shut down, it would need to stop waiting threads from waiting for another task, too - but hopefully you get the general idea.)

这篇关于Threadpool 如何重用线程以及它是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆