线程只运行一次 [英] Thread runs only once

查看:164
本文介绍了线程只运行一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当线程完成时,您不能再使用start()方法运行它:它会抛出异常。有人可以解释,为什么?这样的架构决定背后有什么?

When a Thread is finished, you cannot run it once more, using start() method: it throws an Exception. Could anyone explain, why? What stands behind such an architectural decision?

推荐答案

因为在一个单独的线程中执行代码的方法是不创建一个线程,它链接到什么是线程的系统视图(有关绿色和系统线程之间的区别的无尽细节),但是创建一个 Runnable ,并由Thread执行。

Because the way to have code executed in a separate thread is not to create a thread, which is linked to system view of what is a thread (there are endless details on distinction between green and system threads), but to create a Runnable, and have it executed by a Thread.

为了获得最佳代码(由于线程的创建是耗时的),甚至建议您不要直接让您的Runnable由线程执行,而是由<一个href =http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ExecutorService.html =nofollow noreferrer> ExecutorService ,这将允许你可以使用线程池,而不用担心所有这些细节。

For optimal code (since creation of threads is time-consuming), I would even recommand you not to directly have your Runnable executed by a thread, but rather by an ExecutorService, which will allow you to use a thread pool without bothering about all those details.

这篇关于线程只运行一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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