我有一个包含循环的线程
while(isRunning){
}
isRunning
是一个 boolean 变量,值为 true
,当有人单击按钮时,它会得到 false
,因此它会离开循环并线程的 run()
函数。
我想创建另一个按钮,单击该按钮将重新进入 run()
函数。
我不确定当我离开run()
函数时线程是否会终止或只是停止。
我尝试过使用 thread.run()
但它不起作用。
我也在其他人关于此事的问题中寻找答案,但似乎没有任何帮助。感谢您的帮助
最佳答案
当线程完成处理其代码时,无法重新启动它。您可以:
创建一个新线程并将
Runnable
传递给该线程。如果您需要经常使用
run()
方法,请使用Executor
。您可以使用Executors.newSingleThreadExecutor(),它将为您提供一个工作线程。 (可重复使用的线程)。class Example { static ExecutorService executor = Executors.newSingleThreadExecutor(); static Runnable run = new Runnable() { public void run() { } }; public static void main(String[] args) { //anytime you wanna run that code.. executor.execute(run); } }
关于java - 线程离开后重新启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22581077/