停止特定的java线程 [英] Stopping a specific java thread
问题描述
我有一个按钮addCashier,它正在创建一个名为Cashier的线程,现在这个线程只是每4秒生成一次订单,在线程的run()方法中执行一个while(true)循环。一切都很好,但现在我想添加一个按钮来模拟收银员注销。我在我的while循环onDuty和一个公共函数logOff()中添加了一个布尔变量,它将onTuty bool设置为false以使我退出运行的while循环。我现在的问题是来自我的gui类如何在特定线程上调用函数?每个收银员线程都是在运行时生成的,所以我不知道他们的名字。
I have a button "addCashier" which is creating a thread called "Cashier" now this thread is just simply generating orders every 4 seconds, a while(true) loop in the run() method of the thread. All is good there, but now I want to add a button to simulate cashiers logging off. I added a boolean variable to my while loop onDuty and a public function logOff() which sets this onDuty bool to false to get me out of the run's while loop. My problem now is from my gui class how can I call a function on a specific thread? Each cashier thread has been generated at runtime so I don't know their names.
我希望我有道理。在此先感谢。
I hope I made sense. Thanks in advance.
推荐答案
Thread t = CashierThread(); //keep the reference to thread somewhere...
现在使用内置而不是布尔属性中断标志:
Now instead of a boolean property use built-in interrupted flag:
public void run() {
while(!Thread.currentThread().isInterrupted()) {
//...
}
}
何时你想通过点击按钮来转动线程只需调用:
When you want to turn of the thread by clicking on a button simply call:
t.interrupt();
当然你需要访问 t
来自客户代码的变量。
Of course you need to have access to t
variable from the client code.
这篇关于停止特定的java线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!