How to stop thread ?

Hi all,
Could you tell me pls, how to stop a thread ?
thanks in advance
bye

Well, there is a stop method on the Thread class, but its been deprecated, and its not a good idea to use it. The reason is that you might call stop when your code is in a criticial section (ex. in a sync block).
The best way is to have a method on your class that takes a boolean timeToDie and stores it in an instance variable. timeToDie should start out false. Have your thread check the boolean once in a while and if it ever turns to true then exit your thread appropriately.
That should do it. Good luck!

Similar Messages

  • How to stop thread permanatly after start?

    hello,
    i am using one thread . that thread start with time delay 10 seconds as follow,
    class tableUpdateThread implements Runnable
        Thread thread;
        int i,j;
        tableUpdateThread()
            thread = new Thread (this, "Table updation");
            thread.start();
        public void run()
            System.out.println (" Update thread starts........");
    try
                      System.out.println (" Update thread starts 4........");
                      Thread.sleep(10000);
                  } catch(InterruptedException ee)
                      System.out.println ("");
    }but, in one point in program, i stopped the thread by,
    tableUpdateThread.thread.stop();but, the thread again started after 10 seconds.
    Whhen I go to another panel, I need to stop the thread permanatly.
    But, in panel 1 I need the thread update the JTable every 10 seconds.
    but in panel 2 I need to stop the thread completely.
    how can I do it.
    please help me.

    Thread.stop has been depracated as unsafe.
    The legitimate way for a thread to stop is for it to return from the run() method.
    Typically you do this by interrupting the thread. If the thread is in sleep or wait this will trigger an InterruptedException. If not, it sets a flag, which the thread should check when it does a loop.
    (If a thread calls sleep or wait after being interrupted, it throws InterruptedException immediately.)

  • How to stop threads ???

    Dear all,
    I have a main class in which I declare and start 3 different threads, nothing else.
    When an event occurs in one of the threads, I would like to stop the 2 others and to finish my application ?
    How can I do that ?
    My Main:
    public class client_cc {
    public static Multicast_all multicast_all;
    public static Multicast_zone multicast_zone;
    public static Unicast unicast;
    public static void main(String arg[])
    String multicastall = null;
    int portall=0;
    String multicastzone = null;
    int portzone=0;
    try{
    String temp;
    FileInputStream sonInput = new FileInputStream ("server_config.txt");
    DataInputStream sonData = new DataInputStream (sonInput);
    while ((temp = sonData.readLine()) != null) {
    if(temp.equals("multicast_all")){
    multicastall = sonData.readLine();
    Double valeur = new Double(sonData.readLine());
    portall = valeur.intValue();
    if(temp.equals("multicast_zone")){
    multicastzone = sonData.readLine();
    Double valeur = new Double(sonData.readLine());
    portzone = valeur.intValue();
    sonInput.close();
    }catch(Exception e){}
    // I START THE THREADS
    multicast_all = new Multicast_all(multicastall, portall);
    multicast_all.start();
    multicast_zone = new Multicast_zone(multicastzone, portzone);
    multicast_zone.start();
    unicast = new Unicast();
    unicast.start();
    public static void stop(){
    unicast.stop();
    multicast_zone.stop();
    multicast_all.stop();
    ONE OF THE TREADS:
    public class Unicast extends Thread {
    public Runtime run = java.lang.Runtime.getRuntime();
    public Process proc;
    public Multicast_zone multicast_zone;
    public Multicast_all multicast_all;
    public Unicast() {
    public void run(){
    try{
    DatagramSocket s = new DatagramSocket(10000);
    byte[] buf = new byte[100];
    DatagramPacket recv = new DatagramPacket(buf, buf.length);
    while(true){
    s.receive(recv);
    String message = new String (recv.getData());
    Double valeur = new Double(message.substring(5, 9));
    int size = valeur.intValue();
    message = message.substring(9, size);
    System.out.println(message);
    if(message.equals("server_cpu_reboot ")){
    multicast_all.stop();
    multicast_zone.stop();
    try{
    proc = run.exec("./shutdown.exe -r");
    }catch(java.io.IOException e) {System.out.println(e);}
    stop();
    }catch(Exception e) {e.printStackTrace();}
    }

    Add the following line in ur code whereever u want ur thread to stop
    "STOP U ARROGANT THREAD"
    Simple isn't it?

  • How to stop threads, process, streams when closing a (internal) JFrame?

    Dear all,
    I read a Javaworld article about Runtime.exec(), which will output the process outputs and error outputs to either a file or System.out. Now I want to practice it by outputing the process output/error to a Swing JTextArea. It works fine if the process ends successfully.
    My problem is that I want to stop all the output threads and clear all the streams when user click close JFrame button before the process finished. The code is shown below. Note that this frame is poped up by a click from another main frame. ( it is not exiting the main Swing application). This happened when I want to kill a process when it is running.
    I tried to implements a WindowListener and add
    public void windowClosing(WindowEvent e) to the JFrame.
    Inside this method I used process.destroy() and errorGobbler = null, outputGobbler = null, or outputGobbler.interrupt(), errorGobbler.interrupt(). But all these seems does not work. Sometimes thread was not stopped, sometimes process was not destroyed (because the stream was still print out something), sometimes the error stream was not successfully closed - by printing out interruptted by user error message.
    How can I make sure all the underlying streams and threads, including the PrintStream in StreamGobbler class are closed?
    Again this Frame could be a Dialog or InternalFrame, i.e, when I close the frame, the main frame does not exit!
    import java.util.*;
    import java.io.*;
    class StreamGobbler extends Thread
        InputStream is;
        String type;
        OutputStream os;
        StreamGobbler(InputStream is, String type, JTextArea out)
            this(is, type, null, out);
        StreamGobbler(InputStream is, String type, OutputStream redirect, JTextArea out)
            this.is = is;
            this.type = type;
            this.os = redirect;
        public void run()
            try
                PrintWriter pw = null;
                if (os != null)
                    pw = new PrintWriter(os);
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line=null;
                while ( (line = br.readLine()) != null)
                    if (pw != null)
                        pw.println(line);
                    out.append(type + ">" + line);   
                if (pw != null)
                    pw.flush();
            } catch (IOException ioe)
                ioe.printStackTrace(); 
    public class Test extends JFrame
        private JTextArea output;
        private StreamGobbler outputGobbler;
        private StreamGobbler errorGobbler;
        public Test (String file)
            super();
            output = new JTextArea();
            try
                FileOutputStream fos = new FileOutputStream(file);
                Runtime rt = Runtime.getRuntime();
                Process proc = rt.exec("java jecho 'Hello World'");
                errorGobbler = new
                    StreamGobbler(proc.getErrorStream(), "ERROR", out);           
                outputGobbler = new
                    StreamGobbler(proc.getInputStream(), "OUTPUT", fos, out);
                errorGobbler.start();
                outputGobbler.start();
                int exitVal = proc.waitFor();
                output.append("ExitValue: " + exitVal);
                fos.flush();
                fos.close();       
            } catch (Throwable t)
                t.printStackTrace();
         setSize(400,400);
         show();
    }Thanks !

    Thread.interrupt() doesn't stop a thread. You'll have to read the API for more specifics. You could use something like interrupt to force interruption of the thread for the reason of checking the terminating case though. I believe you would want to use this in the case where operations can take a long time.
    Setting your reference to the thread to be null won't stop the thread since it's running. You just lose your reference to it.
    I believe once the thread stops running your streams will be closed, but possibly not cleanly. Someone who has more knowledge of threads might be able to answer this better, but I would generally say clean up after yourself especially if you are writting out data.

  • How to stop thread in midp

    hi all,
    how could I destroy the thread in MIDP ?
    it always shows true while invoking the method isAlive() on the thread.
    thanx

    A thread die when the run method terminate.
    You can set your thread to null if the loop condition in the run method is like :
    while (currentThread== myThread) {....}

  • How to Stop Thread Within TestStand

    I am a relative "newbie" to TestStand in this aspect.  I am creating an sequence to generate CAN Bus Traffic in hopes of getting to a more accurate throughput measurement.  The Subsequence I am creating is a designed infinite loop and I am specifying that the loop be run in a separate thread from the Execution Options setting.
    My question is how I then kill this thread in the cleanup of my sequence.  Since I plan to run the sequence multiple times would not want to have multiple threads running unchecked on my machine.
    I can't see an easy way to do this.  I imagine something like this has been accomplished before.
    Any suggestions?
    Solved!
    Go to Solution.

    The best way to do this to have your main thread tell the other thread when it is time to exit and then after the main thread has done this it should then wait for the other thread to exit (the waiting will happen automatically if you had the "Automatically wait at end of sequence" checkbox checked on your asynchronous sequence call step).
    One of the easiest ways to do this is to pass a boolean parameter by reference into your asynchronous subsequence and have your subsequence check that boolean periodically to see if it should exit. The main sequence can then set this boolean in its cleanup steps.
    Another way is to use a Synchronization step type such as a notification step type and have your asychronous sequence check for a notification that your main sequence will set in its cleanup.
    It's important that your main sequence wait for the other thread to exit before completing so either use the "Automatically wait at end of sequence" sequence call option or add an explicit wait step to your cleanup of your main sequence after you have notified the other thread to exit.
    Hope this helps,
    -Doug

  • How to stop a thread forcefully. do reply urgent

    i would like to stop the thread . i have used stop() method and also i have tested by giving the threadname = null. but these two not worked . how to stop thread forcefully. urgent.
    with regards

    There is no direct way to stop the thread forcefully. If you have implemented the thread, modify the code so as to break on some flag.
    i.e.
    public void run()
    while (keepRunning)
    ...do some stuff here
    and provide some way to set the boolean keepRunning as false. The loop will exit and the thread will also be destroyed.

  • Stopping threads

    how to stop threads immediately?following is my threading code.when i press the stop button the game stops after one or more generations (John Conway's life game).i have tried the boolean solution i.e. declaring a boolean variable and setting it true or false to start and stop the game.is there a more powerful method than yield to stop the thread?how to solve this problem?
    private Thread lifeThread=null;
    //this is the code used when the start button is pressed
    public void start() {
    if(lifeThread == null)
    lifeThread = new Thread(this);
    lifeThread.start();
    //this is the code for the stop button
    public void stop() {
    if(lifeThread != null)
    lifeThread.yield();
    lifeThread = null;
    //run method
    public void run() {
    while (lifeThread!=null) {
    next();
    gen_num++;
    repaint();
    try {
    lifeThread.sleep( delay );
    } catch (InterruptedException e){}

    no.....thread.stop() is not a good read for your question....ignore the last poster.
    You have the right idea...you simply need to set your boolean in a finer grained way. If you are in a long loop, then you should be checking that boolean value at the top of your loop so you can drop out of the loop immediately when the user requests to stop it.
    So again, right idea, you just need a minor logic change.

  • How to stop the thread?

    Hi,
    How to stop the thread in java. This is my program.
    import java.net.InetAddress;
    public class ThreadPing extends Thread {
         ThreadPing(String pingIP)
              super(pingIP);
              start();
         public void run()
              try
              String pingIP = Thread.currentThread().getName();
              InetAddress inet = InetAddress.getByName(pingIP);
              Boolean get=inet.isReachable(1500);          
              if(get==true)
                   System.out.println(inet.getHostName());               
              }catch(Exception e)
         public static void main(String args[])
              for(int i=1;i<=100;i++)
                   String pingIP = "192.168.1."+i;
                   ThreadPing tp = new ThreadPing(pingIP);
    Thanks in advance.

    The simplest way to stop all the thread is to make all thread daemons and exit the program when you want them to stop.

  • How to stop main thread ?

    Hi,
    Inside my java class, after I launch a GUI, I want to stop this main thread. After user make some choice and close GUI window, then, I want to go back to main thread. I use wait() method inside my class to stop main thread , but it does not work and it give me "IllegalMonitorStateException" error. I met same thing, when user close the GUI window and call method notifyAll(). How to stop main thread for a while and how to go back?? Thanks
    Gary

    Hi,
    you can create a boolean, and create a while loop, with a Thread.sleep(time); when you want to continue, you just have to change the state of your boolean. So you don't hava to exit the main. And you can't restart a run() in a thread. You can run it only once, so try to keep in your run() with an appropriate loop.
    Hope it helps.
    S�bastien

  • How to 'STOP' a running java thread in J2ME?

    Dear All,
    How to 'STOP' a running java thread in J2ME?
    In the middleware viewpoint, for some reasons we have to stopped/destroyed the running threads (we have no information how these applications designed).
    But in J2ME, Thread.destroy() is not implemented. Are there other approaches to solve this problem?
    Thanks in advance!
    Jason

    Hi jason,
    Actually there are no methods like stop() and interrupt() to stop the threads in J2ME which is present in normally J2SE Environment.
    But the interrupt method is introduced in Version 1.1 of the CLDC.
    So, we can handle the thread in two ways.
    a) If it is of single thread, then we can use a boolean variable in the run method to hadle it. so when the particular boolean value is changed , it will come out of the thread.
    for eg:
    public class exampleThread implements Runnable
    public boolean exit = false;
    public void run()
    while(!exit)
    #perform task(coding whatever u needed)
    public void exit()
    exit = true;
    b) If it is of many threads then we can handle using the instance of the current thread using currentThread() method
    for eg:
    public class exampleThread implements Runnable
    public Thread latest = null;
    public Thread restart()
    latest = new Thread(this);
    latest.start();
    public void run()
    Thread thisThread = Thread.currentThread();
    while( latest == thisThread )
    #perform some tasks(coding part);
    public voi d stopAll()
    latest = null;
    while ( latest == thisThread )
    performOperation1();
    if( latest != thisThread )
    break;
    performOperation2();
    Regards,
    Prathesh Santh.

  • My Mail app opens unprompted everytime i reboot or awake my macbook pro from sleep.  This was not an issue until i shut down my laptop for the first time in a while 2 days ago.  ANy ideas how to stop this?

    I recently shut down my MacBook Pro for the first time in a long time.  SInce then, everytime i reboot or awake my laptop from sleep, the Mail app opens unprompted causing my computer to slow down incredibly, and some apps to freeze.  I have no idea how to stop this or why it even started doing this.  Any ideas on how to get it to stop? Thanks!

    I have this problem too with my Macbook Air. Mail opens automatically every time my laptop sleeps. I actually just asked about this in my own thread. However, it is not causing my apps to freeze.

  • How to stop while loop when a specified function is terminated?

    I want to make a program which has 2 thread, one of which is to control some devices, and the other is to measure outputs of the devices.
    To do that, I should make a 2 independent loops, but there comes a problem here.
    I want to terminate 2 loops at the same time, but it's difficult for me to do that, because when I try to notify upper sequence's termination to lower loop by some value change, they have some dependency.
    That's why I need your help. I want to know how to stop lower loop when the upper sequence's termination keeping their independency.
    Please let me know. Thank you.
    Attachments:
    help.JPG ‏200 KB

    Is the upper loop commanding the lower loop at all?  I would think you would have some type of communication between the loops.  Just use that communication to send a stop command.  Or the next best way is to just simply use a notifier.
    There are only two ways to tell somebody thanks: Kudos and Marked Solutions
    Unofficial Forum Rules and Guidelines

  • How to stop showing the pop-up window to change password

    Hi,
    How to stop showing the pop-up windows of changing password if the password is expired in dba_users table. This is related to form6.
    Pls advice.
    Thanks
    Raj

    Raj,
    Please do not start a new thread with the same problem. If you still need help, respond to your former thread, and we will still try to help you. But you haven't provided an answer to why you can't trap the error.
    Re: Trapping of error ora-28001, user expired in daa_users table

  • How to stop irritating auto-reloading of the tabs (pages) [i don't have any extensions or apps]

    Seems like this problem appeared quite often, nevertheless i spent an hour in search of an answer surfing the net, alas, nothing..
    Problem: since today Safari started to reload almost every single page whenever i switch between tabs or sometimes even while im stil on the page. Fot example - i'm watching a movie, stoped it - switched to facebook tab to reply to my friend, then back to the tab with the video & no sooner i get back as the page with video auto-refreshes itself & i have to load movie again & look for the place i stoped watching the video to continue!
    Device & program version: Macbook Pro, bought in july, Safari Version 5.1 (6534.50), No extensions or apps installed, & pls dont' say that it happens on particular pages, i visited the same ones yesterday & everything was ok, since today it's working all weird, and happens within all pages. But in the same time no system - once it reloads the page, other time im switching between the same very tabs it doesn't.
    This is unacceptable & completely useless. Why there are no comments from Apple or Safari team, as if the problem doesnt exist? Not speaking of the problem solving process or tips.
    Please, if someone knows how to stop this nightmare - tell me!!
    Apple-team, I would love to hear your comments & in fact receive some help and get this problem fixed.. :\
    (P.S. - person with the same problem posted a message year before, no effective reply.. - https://discussions.apple.com/thread/2356901?start=0&tstart=0 )
    Sincerily yours,
    Tatevik
    <Email Edited by Host>

    Macbook Pro, bought in july
    If your Mac is runing Lion v10.7 try disabling Resume.
    How To Disable Lion's 'Resume' Feature - MacRumors.com

Maybe you are looking for