How to stop continuous threads in Java

I have a Java application in which I CANNOT PERVERT , which launches java.lang.Thread, which has this method run():

public void run(){
   while(true){
     System.out.println("Something");
   }
}

At a certain point in time I want to stop him. If I use Thread.interrupt(), this will not work. If I use Thread.stop(), it works, but this method is deprecated (therefore, its use is not recommended, since it can be removed from the JVM in new versions).

How to stop such continuous flows in Java?

+2
source share
6 answers

You can implement the interrupt method using a control variable.

volatile :

volatile boolean tostop = false; // Keep the initial value to be false

, .

Thread thread1 = new Thread(){
    public void run() {
        while(!tostop) {
         -- Write your code here --
        }
     }
 }

, :

public void ....{
    //Interrupt code
    tostop = true;
    thread1.sleep(300);  // Give the thread sometime for cleanup
    //Use System.exit(0), if the thread is in main function.
}

, .

+1

java , .

Java- - :

java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=4444 <Your Program>

- :

jdb -attach 127.0.0.1:4444

:

threads

kill, .

kill 0xe2e new java.lang.IllegalArgumentException("er");
+8

: http://download.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html:

, Thread.interrupt?

, . , , , . , - , . , , Thread.interrupt, Thread.stop. " ", -, thread.stop thread.interrupt .

+6

.

( !), System.out println , , (.. ).

EDIT: - println , , Thread.interrupted() true, thread.interrupt().

(.. , InterruptedException), InterruptedException, , RuntimeException:

System.setOut(new PrintStream(System.out) {
    public void println(String s) {
        if (Thread.interrupted()) throw new RuntimeException();
        super.println(s);
    }
});
+3

, JRE. stop() , , 10 . , .

0

, , , , !

final Thread t = getTheThreadToClose();

//Final is important because only in this way you can pass it to the following new Thread

if (t != null && t.isAlive() && !t.isInterrupted()){
    try{
       new Thread(){
           public void run(){
               try{ 
                  t.sleep(3000);//SLEEP INSIDE THE NEW THREAD
               }
               catch(InterruptedException ex){}
           }
       }.start();

       t.interrupt();//INTERRUPT OUTSIDE THE NEW STARTED THREAD
    }
    catch(Exception e){}
}

!

I want to thank all of you for your useful help, especially Venomrld and Toby, who inspired me to solve with their words ;-), and this wonderfoul site, which allowed me ALWAYS to solve all my programming problems.

Thank you all again and happy New Year!

0
source

All Articles