Stopping a specific java thread

后端 未结 4 1664
猫巷女王i
猫巷女王i 2020-12-03 02:07

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(

相关标签:
4条回答
  • 2020-12-03 02:41

    If collecting the reference to all the threads is a problem, One other way could be having a public static synchronized HashMap that has the threadId(random number assigned at runtime to each thread) as the key and the boolean as the value. You can modify the while loop to pick the corresponding boolean value from this centralized Map. This would let you log-off a particular cashier.

    0 讨论(0)
  • 2020-12-03 02:46

    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.

    0 讨论(0)
  • 2020-12-03 02:54
    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.

    0 讨论(0)
  • 2020-12-03 03:03

    You can keep a reference of the Thread object somewhere so that u can call threadObj.logOff()

    If you are not willing to do that then while creating a thred u can assign a unique name to the thread.

    public void run ()
    {
        this.setName(strCashireID);
        ......
    }
    

    At runtime, u can get the thread by:

    Thread getThread(String strCashireID) {
       ThreadGroup threadGroup = Thread.currentThread( ).getThreadGroup( );
       Threads[] threads = new Thread[ threadGroup.activeCount() ];
       threadGroup.enumerate(threads);
       for (int nIndex=0; nIndex<threads.length; nIndex++) {
          if(threads[nIndex] != null && threads.getName().equals(strCashireID) {
             return threads[nIndex];
          }
       }
       return null;
    }
    

    I'll still suggest that u store the thread objects in a hash map instead of enumerating them at runtime.

    0 讨论(0)
提交回复
热议问题