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

Similar Messages

  • How to stop the VI confiugred as thread

    I've configured  two VI as Thread, while running the thread i cant able to access the front pannel so that i cant able to stop my data acquisition application, so how to get the control over front panel while running the thread.
    the thread is used for acquiring the data, and some sequence of function running correctly, but the problem is i cant able to stop the acquisition by event click. some body help me out!!
    Thanks and Regards
    Jagan

    Im not able to get you mike, one functionality of thread is to allow other activities isn't. then why im unable to access the front panel? while running thread, other sequence are running parallely. see im giving one status from thread to front panel through updating one global variable in thread. But it is not updating in front panel. after stoping the application by clicking the "stop" button in menu the app is stopping, again im running the app the status is indicated for the past updation.

  • I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with emails from this thread. I used the action within the thread that says stop following but appears to have no effect I stil

    I have several times tried to stop following a thread in the PDF's forum about security issues and i still keep getting flooded with  emails from this thread. I used the action within the thread that says stop following but appears to have no effect I still keep  getting from 5 to 20 emails daily. Please help!!!!!!!

    This may be helpful: How do I disable email notifications?

  • 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 do I search threads within a specific support community, i.e.. Apple Remote Desktop?

    Very frustrated with new layout of discussion forums...
    How do I search key words within threads within a specific support community?
    For Example I want to search the phrase 'couldn't collect' within the Apple Remote Desktop community.

    Thanks for your response. I'm well aware of the global search field.
    My problem with that is if I search the term 'couldn't collect', (in reference to a very specific Error message generated while running a report via Apple Remote Desktop Task Server) I get a slew of useless hits that have either the words 'couldn't' and/or 'collect' or any variation of those words, such as 'collection'.
    I'm looking for responses that are very specific to Apple Remote Desktop only. I don't have hours to weed through thousands of responses that have no bearing to that at all.
    Searching within specific sub-communities was possible before this new layout. Whatever happened to the booelean searches and searching by phrases and the 'advanced' searches? Do they still exist?

  • 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 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 in java 5 for a real-time system??

    Hi,
    In Java 5, thread.stop is deprecated. We need to modify some variable to indicate that the target thread should stop running. "The target thread should check this variable regularly........"
    We are currently developing a simple real-time operating system using the basic features of java. It is running on top of SunSPOT (JAVA5). My question is I need to stop a thread in a scheduler loop of a real-time operating system. We cannot check it regularly. Otherwise it is not a real-time operating system.Is there anyway else to do this?
    Thanks,
    Qing

    That's rather hard to answer. You say you are writing in Java, but you're writing an OS. BUt what's executing the Java - you need a VM of some form. Is that a real-time or non-real-time VM? How it does things ultimately controls how effectively you can do what you are trying to do.
    The simple answer is that Thread.stop() is deprecated and that it will not stop a thread in all situations anyway - eg trying to acquire a monitor lock. But all Thread.stop does is make an exception pending on the thread, and as the thread executes it polls to see if there is an exception pending. When this happens depends on the VM: it might be after every bytecode; it might be when the thread transitions states (eg thread-in-java, thread-in-vm, thread-in-native) - it all depends. But it is polling - just the same as checking that variable - it's just implicit in the VM rather than explicitly in your code.**
    The RTSJ adds a new form of asynchronous termination requests through the AsynchronouslyInterruptedException (AIE). But it only affects code that explicitly declares that it expects AIE to occur, and there are also deferred sections where the AIE will remain pending. Writing code that can handle AIE is very difficult because the normal Java rules are "bent" and finally blocks do not get executed inside AIE-enabled code.
    So as I said this is very hard to answer, it really depends what exactly you are running on and what you are trying to achieve.
    ** Note: some people used bytecode rewriting tools to add this kind of polling as a post-processing step. Perhaps that is something you might be able to do too.
    David Holmes

  • 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 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 an execution from a method and thread?

    1,
    public void method(){
    if( something is true)
    //I want to stop this method
    //or if something is false, go on
    blablablablabla
    }Does any one know how to solve the above??
    2,
    Thread t = new Thread(){
    public void run(){
    if( something is true)
    //I want to stop and kill this Thread
    //or if something is false, go on
    blablablablabla
    }Again, how do I solve the above??
    I know this is very simple, but I just hit a wall when I encounter this on making a program for my project.
    please help
    thanks alot

    warnerja, for the method, I have tried "return" but
    it does not work... will it work on the run method of
    thread object??
    Secondly, doesn't "break" keyword only stops the
    execution of a loop/condition, but not the method's
    scope??yes. break breaks the loop. I thought your method doesnt have any other code except the condition.
    use return with thread.

  • How could stop this thread that calls an externall function ?

    Hi all.
    i need an help about syncronization of two thread.
    the first one is smt like that
    Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.dynamic) {                    
                                  c.adjustLayout();
                             c.repaint();
                             try {
                                  Thread.sleep(delayMillis);
                             catch (InterruptedException ex) {
                                  // ignore
              t.start();where c.adjustLayout(); & c.repaint(); are syncronized over a astructure called G using syncronized(G)
    now the second thread is:
         Thread t = new Thread(new Runnable() {
                   public void run() {
                        long startTime = System.currentTimeMillis();
                        while (System.currentTimeMillis() - startTime < lifetime) {
                             if (c.updateVisible) {
                                  c.updateVisibleGraph();
                             try {
                                  Thread.sleep(delayMillis);
                                  Thread.yield();
                             catch (InterruptedException ex) {
                                  // ignore
              });where the function c.updateVisibleGraph(); is syncronized over G as well. the problem is that this function, takes seconds, and block thread A and B (both of them ar suyncronized, so if B is running A cannot run).
    how can i stop c.updateVisibleGraph(); in the middle of the exectuion or each 50ms.
    is this possible?
    thanks
    Edited by: ELStefen on 26-ago-2010 16.08
    Edited by: ELStefen on 26-ago-2010 16.11

    isocdev_mb wrote:
    Using a synchronized-block is not designed to give up the lock for little while, it holds the lock until the block ends. Your requirement needs a far more fine-grained approach, quite different from your sketched implementation.
    It would involve quite an amount of guessing of what's behind the G and c your mentioning to suggest a way out. Please elaborate on what you're trying to achieve so that we can suggest how to do that...
    P.S. this forum likes problems to come with a simple working example, which you did not provide and a description of what you'd like to achieve, some context.as i thought, damn.
    Well give a working example is quite complex for the time being. Is a big project and take out this part is quite complex. But i can explain the goal.
    Practically there's a Graph (G)
    this graph is used by 2 thread, one is the update the edges and vertices, adding and removing them. the other one thread is the painter of the graph.
    the problem is when the first thread is updating the structure of G, sometimes this operation takes time (seconds) and being synchronized on G it blocks the paint thread as well.
    the thing that i would like to have is keep the painting working each tot millisecond. the updating thread works when necessary. if the update operation takes to long, it has to be stopped in the middle (and it has to restart after the paint) in a way that the paint thread can be executed.
    as the code is, and as you said, synchronizing the entire block code cannot works as i want.
    is this more clear? any clue about how can i solve this?
    many thanks
    Edited by: ELStefen on 27-ago-2010 12.43

  • How to stop the 2nd thread when 1st thread caught exception.

    Hello Friends,
    I have written a java program using Thread.
    In this program i have created two separate threads.
    For example Thread1 and Thread2.
    During execution of both threads,
    If any exception comes on Thread1 or Thread2, the other thread should not be continued its execution. Suddenly the other thread has to interrupted its execution.
    How to do this. If any body know the way to do this, please help me.
    Rgds
    tskarthikeyan

    Try this. It was working Fine.
    public class ThreadComm {
         public static volatile boolean exceptionThrown= true;
         public static void main(String[] args) {
              Thread t1 = new Thread(new Runnable() {
                   public void run () {
                        try {
                             /*if (exceptionThrown) {
                                  System.out.println("First Thread Interrupted");
                                  return;
                             for(int i=1;i<=5000;i++){
                                  System.out.println("FirstThread>>"+i);
                                  if(i==2500) {
                                       throw new Exception("First Thread Interrupted");
                        }catch(Exception e) {
                             exceptionThrown = false;
              Thread t2 = new Thread(new Runnable() {
                   public void run() {
                        try {
                             /*if (exceptionThrown) {
                                  System.out.println("Second Thread Interrupted");
                                  return;
                             for(int i=1;i<=1000;i++){
                                  System.out.println("SecondThread>>"+i);
                                  if(i==777) {
                                       throw new Exception("Second Thread Interrupted");
                             int i=0;
                             while(exceptionThrown && i<=5000) {
                                  System.out.println("SecondThread>>"+i);
                                  if(i==4000) {
                                       throw new Exception("Second Thread Interrupted");
                                  i++;
                        }catch(Exception e) {
                             exceptionThrown = true;
              t1.start();
              t2.start();
    }

Maybe you are looking for