Thread: how to stop it?

I'm new with thread and I don't understand some things about that.
For example: when I create a Class that extends Thread class I must override the method run(), right? After when I call the method start() from the Class the thread runs in a never-ending cycle? How can I stop it?
The example code:
public class MyClass extends Thread {
    private int value;
    public MyClass() {
        value = 0;
    public void run() {
        value++;
}Does the class continue to do the addition until it will throw an exception (when the max value of int type is reached)?
Message was edited by:
Lukyan

Try to run it and see, no?Quoting myself ... I did not mean to be facetious. I really thought that actually running the code would be the clearest way of "seeing" the results. Better answers both before and after mine have provoked me to add the following:
It is very common to code the actual guts of your "Thread" similar to this:
private boolean run = true;
public void run() {
  try {
    while (run) {
      doMethodA();
      doMethodB();
  } catch(InterruptedException ie) {
    doMethodC(); // or print the stack trace or something
private void doMethodA() {
private void doMethodB() {
  if ( "bad".equals(condition) )
    run = false;
}

Similar Messages

  • Javafx Multi Threading - How to stop a thread

    Hi,
    I'm working on a Javafx and Java based chat client. To avoid GUI freezing I have put all "business logic" calls to Java using the Runnable feature. Everyting works ok, but when for example disconnecting the chat client I would also like to stop this specifc thread, avoid building up unused threads. I have tried using .stop() but it looks like its being ignored.
    Here my code:
    main.fx:
    progressIndicator.visible = true;
            var listener = FXListener_interface_connection {
                        override function callback(errorCode, errorMessage): Void {
                            //do something
                            if (errorCode != 200) {
                                setIcn(errorMessage);
                            } else {
                                progressIndicator.visible = false;
                                imageView9.visible = true;
                                openMessageListener();
                                rosterListener();
                                var ooo = ScaleTransition {
                                            duration: 0.2s
                                            node: imageView9
                                            byX: 0.6 byY: 0.6
                                            repeatCount: 8 autoReverse: true
                                ooo.play();
            var connect = FXListener_connection {
                        listener: listener
                connect.start();listener_connection.fx:
    public class FXListener_connection extends JavaTaskBase {
        public var listener: FXListener_interface_connection;
        protected override function create() : RunnableFuture {
            new Java_callback_connection(listener);
    }connection_interface.java
    public interface FXListener_interface_connection {
        public void callback(Integer errorCode, String errorMessage);
    }connection_callback.java
    public class Java_callback_connection implements RunnableFuture {
        private static FXListener_interface_connection listener_interface_connection;
        public Java_callback_connection(FXListener_interface_connection listener_interface_connection) {
            this.listener_interface_connection = listener_interface_connection;
        @Override
        public void run() throws Exception {
            //call function xmpp_connect()
            static_variables.xmpp.xmpp_connect();
        public static void connection(final Integer errorCode, final String errorMessage) {
            Entry.deferAction(new Runnable() {
                @Override
                public void run() {
                    listener_interface_connection.callback(errorCode, errorMessage);
    }

    jdevel doesn't let me debug;
    public class ProgressBarModel extends BoundedRangeModel {
    BooleanValueWrapper stopFlag = new BooleanValueWrapper(false);
    BooleanValueWrapper stopFlag2 = new BooleanValueWrapper(false);
    IntValueWrapper value = new IntValueWrapper(0);
    Thread newProgress = null;
    Thread newProcessFile = null;
    public void start(ActionEvent e) {
    value.setValue(0);
    stopFlag.setValue(false);
    ProgressSimulator progressSimulator = new ProgressSimulator();
    newProgress = new Thread(progressSumulator);
    newProgress.start();
    ProcessFileThreadMe processFileThreadMe = new ProcessFileThreadMe();
    newProcessFile = new Thread(processFileThreadMe);
    newProcessFile.start();
    class ProgressUpdater implements Runnable
    public void run(){
    try
    System.out.println(" ProgressUpdater is running");
    //stop fag is true if it is set to true or if value is equals or greater
    //than maximum
    try { 
    stopFlag.setValue(stopFlag.getValue() == true? true : (value.getValue() < maximum? false:true));
    //run in loop until stop condition is met. Make sure system doesn't
    //fail if values are initially set to the same value
    while (!stopFlag.getValue() && value.getValue() != maximum) {
    newProgress.interrupt();
    newProgress = null;
    } catch(Exception e) {
    stopFlag.setValue(true);
    stopFlag2.setValue(true);
    class ProcessFileThreadMe implements Runnable
    public void run(){
    System.out.println(" ProcessFileThreadMe is running");
    try
    if(stopFlag2.getValue() == true) {
    // interrupt this thread
    // set it to null
    return;
    bean.persisit(value, stopFlag);
    newProcessFile.interrupt();
    newProcessFile = null;
    catch (Exception exc)
    stopFlag.setValue(true);
    stopFlag2.setValue(true);
    exc.printStackTrace();
    In the bean the v alue is incremented
    Edited by: user597294 on Jul 21, 2011 6:33 AM

  • New Socket takes too long / how to stop a Thread ?

    Hello to everyone,
    I have a problem that I have been hunting this ol' Sun website all day for a suitable answer, and have found people who have asked this same question and not gotten answers. Finally, with but a shred of hope left, I post...
    My really short version:
    A call to the Socket(InetAddress,int) constructor can take a very long time before it times out. How to limit the wait?
    My really detailed version:
    I have a GUI for which the user enters comm parameters, then the program does some I/O while the user waits (but there is a Cancel button for the Impatient), then the results are displayed. Here is quick pseudocode (which, by the way, worked great before there were Sockets in this program -- only serial ports):
    Main (GUI) thread:
         --> reset the stop request flag
         --> calls workerThread.start(), then brings up a Cancel dialog with a Cancel button (thus going to sleep)
         --> (awake by dialog closing -- dialog may have been closed by workerThread or by user)
         --> set stop request flag that worker thread checks (in case he's still alive)
         --> call workerThread.interrupt() (in case he's alive but asleep for some reason (???))
         --> call workerThread.join() to wait for worker thread to be dead (nothing to wait for if he's dead already)
         --> display worker thread's result data or "Cancelled..." information, whichever worker thread has set
    Worker thread:
         --> yield (to give main thread a chance to get the Cancel Dialog showing)
         --> do job, checking (every few code lines) that stop request flag is not set
         --> if stop request, stop and set cancelled flag for Main thread to handle
         --> if finish with no stop request, set result data for Main thread to handle
         --> take down Cancel Dialog (does nothing if not still up, takes down and wakes main thread if still up)
    THE PROBLEM: Worker thread's job involves doing IO, and it may need to instantiate a new Socket. If it is attempting to instantiate Socket with bad arguments, it can get stuck... The port int is hardcoded by the program, but the IPAddress must be typed by user.
    If the arguments to Socket(InetAddress, int) constructor contain a valid-but-not-in-use IP address, the worker thread will get stuck in the Socket constructor for a LONG time (I observed 1m:38s). There is nothing the Main thread can do to stop this wait?
    EVEN WORSE: If the user clicks the Cancel Button during this time, the dialog goes away soon/immediately, but then the GUI appears to be hanging (single-threaded look) until the long wait is over (after which the "Cancelled..." info is displayed).
    MY QUESTION: Is there nothing the Main thread can do to stop this wait?
    Your answers will be sincerely appreciated. Despite my hopeless attitude (see above), the folks at this forum really have yet to let me down ...
    /Mel

    http://developer.java.sun.com/developer/technicalArticles/Networking/timeouts/

  • 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 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!

  • 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.

  • How to stop a thread within a thread.

    I have two threads. A progress Bar thread and it starts yet another thread.
    In the exception handler of the second thread how do I stop both the threads. thread.interrupt() seems to have to effect.
    Thanks,
    Veena

    jdevel doesn't let me debug;
    public class ProgressBarModel extends BoundedRangeModel {
    BooleanValueWrapper stopFlag = new BooleanValueWrapper(false);
    BooleanValueWrapper stopFlag2 = new BooleanValueWrapper(false);
    IntValueWrapper value = new IntValueWrapper(0);
    Thread newProgress = null;
    Thread newProcessFile = null;
    public void start(ActionEvent e) {
    value.setValue(0);
    stopFlag.setValue(false);
    ProgressSimulator progressSimulator = new ProgressSimulator();
    newProgress = new Thread(progressSumulator);
    newProgress.start();
    ProcessFileThreadMe processFileThreadMe = new ProcessFileThreadMe();
    newProcessFile = new Thread(processFileThreadMe);
    newProcessFile.start();
    class ProgressUpdater implements Runnable
    public void run(){
    try
    System.out.println(" ProgressUpdater is running");
    //stop fag is true if it is set to true or if value is equals or greater
    //than maximum
    try { 
    stopFlag.setValue(stopFlag.getValue() == true? true : (value.getValue() < maximum? false:true));
    //run in loop until stop condition is met. Make sure system doesn't
    //fail if values are initially set to the same value
    while (!stopFlag.getValue() && value.getValue() != maximum) {
    newProgress.interrupt();
    newProgress = null;
    } catch(Exception e) {
    stopFlag.setValue(true);
    stopFlag2.setValue(true);
    class ProcessFileThreadMe implements Runnable
    public void run(){
    System.out.println(" ProcessFileThreadMe is running");
    try
    if(stopFlag2.getValue() == true) {
    // interrupt this thread
    // set it to null
    return;
    bean.persisit(value, stopFlag);
    newProcessFile.interrupt();
    newProcessFile = null;
    catch (Exception exc)
    stopFlag.setValue(true);
    stopFlag2.setValue(true);
    exc.printStackTrace();
    In the bean the v alue is incremented
    Edited by: user597294 on Jul 21, 2011 6:33 AM

  • 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.

  • 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.

  • 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

  • How to stop the running infospoke

    Hi Experts,
    there is a infospoke is still running so long time, it's incorrect, i'll cancel it as kick off the dependenies, i have no idea to how to stop the running infospoke. Anybody could tell me how to do it. thanks in advance.

    hi denny,
       Go to SM37 , find the job , stop the process
    or
       To stop the job find the job with the help of the request name ( TC - SM37 ),then in the job Details find the PID .
    find the process in the process Overview (SM50 / SM51 ).
    Set the restart to NO and Cancel the process without core
    u can also see these threads that are already posted:
    stopping v3 run job LIS-BW-VB_APPLICATION_02_010
    how to cancel or change the background job which is scheduled
      In SM37, for the job , click on Step button. Then from the menu Goto > variant. You can see the process chain name here.
    sure it helps
    Thanks
    Varun CN

Maybe you are looking for

  • Does PSE11 show HDR exif data for a Canon 5D Mark III?

    I have taken some pictures with the HDR feature on my Canon 5D Mark III. The HDR image that the camera creates does not show that it was created using the camera's HDR feature when viewed with PSE11. The Canon Software that came with my camera is Ima

  • Error : Maximum Open Cursors Exceded

    Hi! The error appear in that check out or check an objet using OSCM. At first I cna do it but when i trying to check in or out files the messages appear. I don´t understand why and for waht action it appear. Any suggestion?? Thanks! Matias

  • When opening a new tab, babylon search opens by default (which I Hate), How can I change it?

    Babylon search and tool bar, got installed in my computer when I installed some other program (Ares). And now there is no way I can get rid of it (of Babylon). Please help. It is annoying.

  • What oracle best practices in mapping budgeting to be implement at item

    Dear Consultant's Really i need you values Consultantancy What oracle best practices in mapping budgeting to be implement at item category level or item level I want to check fund at encumbrance account according to item level Case: I have there item

  • Cannot find the assembly Oracle.DataAccess

    Ok, We have a dataset generation class that runs remotely as a windows service in VB.NET. On some machine, when they have connected and are running a query, they get an exception thrown Cannot find the assembly Oracle.DataAccess, Version=9.2.0.20, Cu