我有一个“addCashier”按钮,它正在创建一个名为“Cashier”的线程,现在这个线程只是简单地在线程的run()方法中每隔4秒产生一次,一个while(true)循环。 一切都很好,但现在我想添加一个按钮来模拟收银员注销。 我在我的while循环onDuty和一个公共函数logOff()中添加了一个布尔变量,它将onDuty布尔值设置为false以使我脱离run的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...现在使用内置中断标志而不是布尔属性:
public void run() { while(!Thread.currentThread().isInterrupted()) { //... } }当您想通过单击按钮来转动线程时,只需调用:
t.interrupt();当然,您需要从客户端代码访问t变量。
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();Of course you need to have access to t variable from the client code.
更多推荐
发布评论