Stopping a specific java thread

后端 未结 4 1673
猫巷女王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: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.

提交回复
热议问题