Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

multithreading - Stopping a specific java thread

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...