停止特定的Java线程(Stopping a specific java thread)

编程入门 行业动态 更新时间:2024-10-28 18:32:01
停止特定的Java线程(Stopping a specific java thread)

我有一个“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.

更多推荐

本文发布于:2023-08-07 05:09:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1460857.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:线程   Stopping   Java   thread   java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!