Guys, there is a thread in which there are about 100 methods. Which in turn goes on for 10 minutes. Such a test frame.

Thread testRunningThread = null; 

and challenge

 testRunningThread = new Thread(util); testRunningThread.start(); 

Stop passes so

 if (testRunningThread != null) { util.setInterruptTests(new AtomicBoolean(true)); } 

But it is very necessary to stop the thread immediately. Without waiting for the end of the end of the robots currently running method. How to spend it?

  • do checks more often? - KoVadim
  • no checks. The user wants to just stop the execution. And then you need an immediate exit. - bboybboy
  • 3
    You need to make the methods shorter and do checks whether you need to quit more often. Either use interrupt (read a great article on this topic ). - KoVadim
  • one
    You do not have the right to stop the flow. It can be in any execution phase, for example, in native code holding a global heap memory lock. The flow should cooperate: stop by itself, respond faster to a request to stop working. --- The user does not care if the stream is alive or dead. If he wants to terminate the application, close all windows and wait until the threads run without UI. - VladD

1 answer 1

Quote from skipy.ru/technics/synchronization.html :

Option one is to use an existing mechanism. The class Thread has such a method - interrupt. This method sets some flag in the wilds of native code. In the future, the status of this flag can be checked using the isInterrupted method. There is also a static interrupted method that checks for the current thread. Please note - calling this method resets the flag, which implies the responsibility of the developer to handle this situation.

The second embodiment of the stopping method (as well as the suspension) is to make an analogue interrupt, but with your hands. Those. to organize flags in their own implementation of the flow — to stop and suspend — and expose them by calling methods from the outside. The procedure is the same - check the installation of flags.