且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

停止并重新启动已经运行的线程

更新时间:2021-07-24 21:31:43

Java 线程不可重新启动.对于您想要实现的目标,您可以每次创建一个新线程,或者您可以查看 ExecutorService.只需创建一个单线程执行程序 (Executors.newSingleThreadExecutor),并在每次需要运行时将可运行对象提交给它.

Java threads are not restartable. For what you are trying to achieve, you could create a new thread each time, or you could look at an ExecutorService. Just create a single threaded executor (Executors.newSingleThreadExecutor), and submit your runnable to it every time you need it to run.

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(runnable);