Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 507
mikeyP Avatar asked Dec 21 '22 07:12

mikeyP


2 Answers

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.

like image 169
Tomasz Nurkiewicz Avatar answered Jan 10 '23 07:01

Tomasz Nurkiewicz


You can store each thread's reference into a HashMap - along with its id or Name as the key. Later when you want to deal with one particular Cashier thread , use the Name or id to fetch the corresponding Thread from the HashMap and call the appropriate logOff() method on it.

like image 42
Bhaskar Avatar answered Jan 10 '23 06:01

Bhaskar