Thread Interruption

Hi,
If a Parent thread intiates child thread ,and if the child thread runs in infinite loop. If the child thread encountered an exception ,does it come out or still it runs in infinite loop throwing exception. Can i know how to stop a thread when it found some exception?

I'm not sure I understand your question, but I'll say this:
A thread starts at the beginning of its run() method, works its way to the end, then stops. It's possible that the run() method is written in such a way that it's impossible to reach the end, although I'd argue that's bad coding. It's also possible that an exception (or more generally, a Throwable) is thrown somewhere, in which case control flow will change somehow, either into a catch block, or up the call stack, or both. I believe that an exception will never cause control flow to go into the thread that created the current thread, if that's what you're asking.
If you want an exception to stop a thread, just use a try/catch. If the thread has a while loop to keep it going indefinitely or until a certain condition (this is typical), then place the try/catch accordingly, perhaps:
public void run() {
  try {
    while(continue_to_loop) { // continue_to_loop is a boolean instance variable
      // do your stuff
  } catch (TheExceptionYoureConcernedAbout e) {
    // handle it
}If the exception happens, the while loop ends and does not restart.

Similar Messages

  • DatagramSocket.receive() and Thread.interrupt() - Inconsistent behavior

    Hi,
    I currently have an application that does in a seperate Thread receive udp packets in a loop around a Datagramsocket.receive(). Whenever a state change should occur, the thread is being interrupted by Thread.interrupt() in order to exit the DatagramSocket.receive().
    That works nicely on the solaris version of the jvm (1.5.0-11) on x86 and sparc but it does not work on linux intel (i386 and amd64). There the receive simply ignores the interrupt.
    What is the intended behavior ?
    Do I have to move to timeOuts on each receive (which hinders fast state changes as timeouts have to occur and the loop has to be timeouted very often in order to be fast).
    Little tests say: (java 1.5)
    Linux 2.6.18 (32/64 Bit) : no interrupt
    FreeBsd (32/64 Bit): interrupt works
    Solaris 10 (sparc/64x86): interrupt works
    MacOs 10.4: no interrupt
    On Linux 2.6.18, java 1.4 - interrupt works.
    At least a consistent behavior is missing!
    J�rn
    Here is the code:
    SubThread.java:
    package test;
    import java.net.*;
    import java.io.*;
    public class SubThread extends Thread {
         public DatagramSocket ds;
         public boolean quit=false;
         public SubThread() {
              super();
              try {
                   ds = new DatagramSocket();
              } catch (Exception E) {
                   System.out.println("new DS failed: "+E.getMessage());
                   System.exit(-1);
         public void run() {
              byte[] buf = new byte[1000];
              DatagramPacket p = new DatagramPacket(buf, buf.length);
              System.out.println("Started subThread !");
              while (!quit) {
                   try {
                        ds.setSoTimeout(10000); // 10 Seconds
                        ds.receive(p);
                   } catch (SocketTimeoutException E) {
                        System.out.println("ST: Hit timeout !");
                   } catch (InterruptedIOException E) {
                        System.out.println("ST: Interrupted IO Works !: "+E.getMessage());
                        quit=true;
                   } catch (Exception E) {
                        System.out.println("ST: Exception: "+E.getMessage());
              System.out.println("Ended subThread !");
    }Test.java:
    package test;
    public class Test {
         static Integer a = 1;
         public static void main(String[] args) {
              SubThread st = new SubThread();
              st.start();
              try {
                   synchronized (a) {
                        System.out.println("Starting wait (1s) !");
                        a.wait(1000);
                        System.out.println("Sending interrupt()");
                        st.interrupt();
                        a.wait(1000);
                        if (!st.quit) {
                             System.out.println("As interrupts do not work, terminating by timeout !");
                             st.quit=true;
                             System.out.println("Waiting for end!");
                        } else
                             System.out.println("Ending !");
              } catch (Exception E) {
                   System.out.println("Exception: "+E.getMessage());
    }

    What is the intended behavior ?The intended behaviour is defined in http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#interrupt()
    ' If this thread is blocked in an I/O operation upon an interruptible channel then the channel will be closed, the thread's interrupt status will be set, and the thread will receive a ClosedByInterruptException.'
    DatagramSocket not being an InterruptibleChannel, this piece doesn't apply. None of the other pieces apply either, so the fallback applies:
    ' If none of the previous conditions hold then this thread's interrupt status will be set.'
    If you're getting an interrupted read() on one platform, that's a bonus, but it's not the defined behaviour.
    Use a DatagramSocket derived from DatagramChannel.open().socket() and it should work on all platforms.

  • How does thread.interrupt() work

    What I would like to do is cause an interrupt of the main thread in the Timer thread and catch the interrupt in the main thread, but the 'catch(InterruptedException)' in the main thread has an unreachable error. I am confused. The 'interrupted()' is not static and so I assume that 'thread.interrupt()' will cause and interrupt in 'thread', the main thread, but I can't seem to be able to catch it. Any idea what I'm doing wrong and how to fix the problem?
    public static Message receive(int milliseconds, BufferedInputStream in) {
        Message message;                         // Message return value
        class Timer implements Runnable {
            Thread thread;                       // Calling thread
            int    milliseconds;                   // Timeout in milliseconds
             public Timer(Thread thread, int milliseconds) {
                this.thread = thread;
                this.milliseconds = milliseconds;
            } // public Timer(Thread thread, int milliseconds)
            @Override
            public void run() {
                try {
                    Thread.sleep(milliseconds);
                    thread.interrupt();         // timer expired before input achieved
                } catch (InterruptedException e) {
                    // input received before timer expired
            } //  public void run()
        } //Timer implements Runnable
        if (milliseconds <= 0)
            message =  receive(in);
        else {
            try {
                Thread timer = new Thread(new Timer(Thread.currentThread(), milliseconds));
                timer.start();
                message = receive(in);
                timer.interrupt();
            } catch (InterruptedException{
                // Do something, in desperation if you have to.
        return message;
        } // Message receive(int time, BufferedInputStream in)
    }

    The current code has a 'Thread.interrupted()' in it, see below. Unfortunately, the if statement is never executed (crash and crumble). The code which actually input a message, something like
        BufferedInputStream in = read(header, 0, HEADER_SIZE);Won't let me put a try/catch statement around it, same reason - unreachable code.
    So where I'm at is that I don't understand what I have to do to do a thread.interrupt() and then catch it.
    public static Message receive(int milliseconds, BufferedInputStream in) {
        Message message;                         // Message return value
        class Timer implements Runnable {
            Thread thread;                       // Calling thread
            int    milliseconds;                   // Timeout in milliseconds
             public Timer(Thread thread, int milliseconds) {
                this.thread = thread;
                this.milliseconds = milliseconds;
            } // public Timer(Thread thread, int milliseconds)
            @Override
            public void run() {
                try {
                    Thread.sleep(milliseconds);
                    thread.interrupt();         // timer expired before input achieved
                } catch (InterruptedException e) {
                    // input received before timer expired
            } //  public void run()
        } //Timer implements Runnable
        if (milliseconds <= 0)
            message =  receive(in);
        else {
                Thread timer = new Thread(new Timer(Thread.currentThread(), milliseconds));
                timer.start();
                message = receive(in);
                timer.interrupt();
            if (Thread.interrupted() {
                // Do something, in desperation if you have to.
        return message;
        } // Message receive(int time, BufferedInputStream in)
    }

  • EOF Exception with Thread interrupts ?

    EOF file Exception for RandomAccess.readFully() call. All the parameters are valid.
    Is it possible/Any one seen to get EOF exception If another Thread interrupt the thread
    which is doing I/O(READ).
    I am running on SUN jdk131/Solaris8?
    Thanks
    -suresht

    Hint if working with threads on reading data from files just synchronize the methods, like
    public synchronized readData(...){...}
    if you do not do that a thread is reading and when it breaks down it will locks the method(in your case the file will not been closed and if a file is not closed it cannot be opened by another thread/method/object/whatever)

  • Using thread interrupts

    My application consists of a progress bar that updates every second. Here is the class:    static class UpdateProgress extends Thread
            public void run ()
                try
                    for (int i = 0; i < GUI.songProgress.getMaximum (); i++)
                        Thread.currentThread ();
                        Thread.sleep (1000);
                        GUI.songProgress.setValue (i);
                catch (Exception e)
                    System.out.println ("Error: " + e.getMessage ());
            UpdateProgress ()
        } To start the thread I call:         new UpdateProgress ().start (); and to stop it I call:         new UpdateProgress ().interrupt (); The problem I am having is that when I call the interrupt() method, it doesn't interrupt because the progress bar keeps counting up. Should I be doing something other than interrupt()?

    Oh I see, like:     UpdateProgress updateProgress = new UpdateProgress(); and then call: updateProgress.start(); and updateProgress.interrupt();

  • Why can't I interrupt the main thread from a child thread with this code?

    I am trying to find an elegant way for a child thread (spawned from a main thread) to stop what its doing and tell the main thread something went wrong. I thought that if I invoke mainThread.interrupt() from the child thread by giving the child thread a reference to the main thread, that would do the trick. But it doesn't work all the time. I want to know why. Here's my code below:
    The main class:
    * IF YOU RUN THIS OFTEN ENOUGH, YOU'LL NOTICE THE "Child Please!" MESSAGE NOT SHOW AT SOME POINT. WHY?
    public class InterruptingParentFromChildThread
         public static void main( String args[] )
              Thread child = new Thread( new ChildThread( Thread.currentThread() ) );
              child.start();
              try
                   child.join();
              catch( InterruptedException e )
    // THE LINE BELOW DOESN'T GET PRINTED EVERY SINGLE TIME ALTHOUGH IT WORKS MOST TIMES, WHY?
                   System.out.println( "Child please!" );
              System.out.println( "ALL DONE!" );
    The class for the child thread:
    public class ChildThread implements Runnable
         Thread mParent;
         public ChildThread( Thread inParent )
              mParent = inParent;
         public void run()
              System.out.println( "In child thread." );
              System.out.println( "Let's interrupt the parent thread now." );
              // THE COMMENTED OUT LINE BELOW, IF UNCOMMENTED, DOESN'T INVOKE InterruptedException THAT CAN BE CAUGHT IN THE MAIN CLASS' CATCH BLOCK, WHY?
              //Thread.currentThread().interrupt();
              // THIS LINE BELOW ONLY WORKS SOMETIMES, WHY?
              mParent.interrupt();
    }

    EJP wrote:
    I'm not convinced about that. The wording in join() suggests that, but the wording in interrupt() definitely does not.Thread.join() doesn't really provide much in the way of details, but Object.wait() does:
    "throws InterruptedException - if any thread interrupted the current thread +before+ or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown."
    every jdk method i've used which throws InterruptedException will always throw if entered while a thread is currently interrupted. admitted, i rarely use Thread.join(), so it's possible that method could be different. however, that makes the thread interruption far less useful if it's required to hit the thread while it's already paused.
    a simple test with Thread.sleep() confirms my expected behavior (sleep will throw):
    Thread.currentThread().interrupt();
    Thread.sleep(1000L);

  • Some questions on interrupts, threads etc

    Havng gone through some documentation on interrupt, kernel level threads etc in WDF, I got a couple of questions:
    1)  Can a hardware interrupt be preempted by another interrupt in a single processor system?
    2)  What exactly is the difference between thread preemption and thread interrupt? Doesnt both mean stopping the current thread and putting it aside?
    3)  When an iterrupt is handled by an ISR, does the ISR always have to  schedule  a DCP? If the ISR itself can handle the interrupt, is the DPC needed?
    4) I understand that spin locks are used for synchronisation at IRQL <=DISPATCH_LEVEL. EVT_WDF_IO_QUEUE_IO_WRITE works at <= DISPATCH_LEVEL. If I set Synchronisation scope of a write queue as SynchronisationScopeQueue, should I still go for a spin
    lock, if the write callback and say an ioctl callback uses a shared resource?
    5 )Kernel dispatcher objects are mutex, timer, event, semaphore etc. But If i use a fast mutex or guarded mutex or oridinary mutex using say, KeAcquireFastMutex() isnt that then a kernel dispatcher object? What this distinction?  Why should we go explicitly
    go for kernel dispatcher object?
    6) How can timers be used for kernel level synchronisation? How different is this from timers created using WdfTimerCreate()?
    7)  It is said that "Never wait on a kernel dispatcher object in any driver routine that can be called at IRQL>=DISPATCH_LEVEL.". Does it mean
    we should not use synchronisation mechanisms in this level? Or if we can use, should the thread try to acquire a lock with  a zero wait time? And proceed if it could acquire the lock and return if the lock was not acquired?
    8) I understand that in order to execute an interrupt, a driver does not create any special threads but use a thread that happens to be running at the moment( arbitrary thread ) . My question is, in what way is this accomplished? What aspect of the arbitrary
    thread is the interrupt using ? The arbitrary thread must obviously have been written for another purpose.

    To answer the questions:
    #1   An interrupt service routine (ISR) running a lower IRQL may be interrupted by another ISR running at a higher level.
    #2   Having never heard of a thread interrupt, all I can say here is that a thread may be pre-empted for a lot of reasons.
    #3   An ISR does not have to schedule a DPC unless it needs to do work that it cannot do at high IRQL.
    #4   Assuming that the Write and IOCTL are on seperate queues, yes you need a a lock to protect shared resources.
    #5   As the name implies kernel dispatcher objects allow scheduling (i.e. dispatching of another thread), while things like spinlocks do not. 
    #6    Timers are just another dispatching object, i.e. one can wait on them the same way one waits on a mutex or a semaphore.  A WDF TIMER is basically a wrapper around a regular timer to take care of some of the housekeeping (particularily
    with respect to stopping the driver etc)
    #7     If a routine is running at DISPATCH_LEVEL you are limited to spin locks for synchronization. You can with a zero timeout check the status of a kernel dispatcher object.   In general, routines like this should be
    designed to only use spinlocks.
    #8    An arbitrary thread is just that, it may be a thread in any process. Basically a currently running thread is grabed and used to run the interrupt so that the scheduler which has overhead and is not designed to run at interrupt level
    IRQL's does not need to run.
    Don Burn Windows Filesystem and Driver Consulting Website: http://www.windrvr.com Blog: http://msmvps.com/blogs/WinDrvr

  • Interrupting a Thread in a Remote Object?

    HI,
    I am trying to get some thread synchronization to happen between a client and a remote RMI object. Essentially what I am trying to accomplish, is that if I interrupt a call on a blocking method in the remote object, I want the thread to throw the InterruptException. For example, the following code represents what I am trying to accomplish:
    package bca.test.rmi;
    import java.rmi.Naming;
    import java.rmi.Remote;
    import java.rmi.RemoteException;
    import java.rmi.server.UnicastRemoteObject;
    public class InterruptThreadApp {
    RemoteBlockingObjectInt remote = null;
    public static void main(String[] args) throws Exception {
    //Create the remote object
    RemoteBlockingObject obj = new RemoteBlockingObject();
    //bind it to the registry
    Naming.rebind("rmi://localhost/blocking", obj);
    //start the client, or the thread which will access the blocking call remotely
    InterruptThreadApp app = new InterruptThreadApp();
    Thread blocking = null;
    //wait for the thread to start
    synchronized ( app ) {
    blocking = app.startClient();
    app.wait();
    Thread.sleep(2000);
    //now interrupt the thread (note: the remote object should be blocking in
    //the blockingMethod().. this should produce an InterruptException?
    blocking.interrupt();
    public Thread startClient() {
    Thread t = new Thread("Client") {
    public void run() {
    try {
    //get a handle to the stub
    remote = (RemoteBlockingObjectInt) Naming.lookup("rmi://localhost/blocking");
    //now make a call to the blocking method, but first wake up the client
    synchronized ( InterruptThreadApp.this ) {
    InterruptThreadApp.this.notify();
    //now make the blocking call
    remote.blockingMethod();
    catch (InterruptedException e) {
    System.out.println("WooHoo! This is what we want! But it never gets thrown :(");
    catch (Exception e) {
    e.printStackTrace();
    t.start();
    return t;
    package bca.test.rmi;
    import java.rmi.server.UnicastRemoteObject;
    import java.rmi.RemoteException;
    import java.rmi.Remote;
    public class RemoteBlockingObject extends UnicastRemoteObject implements RemoteBlockingObjectInt {
    Object obj = new Object();
    public RemoteBlockingObject() throws RemoteException {
    super();
    public void blockingMethod() throws RemoteException, InterruptedException {
    synchronized (obj) {
    System.out.println("About to block.. so we can be interrupted later");
    obj.wait();
    interface RemoteBlockingObjectInt extends Remote {
    public void blockingMethod() throws RemoteException, InterruptedException;
    When I make a call to "remote.blockingMethod()", it blocks in the remote object (buy just "wait" ing). I want to interrupt this thread, by issuing an Thread.interrupt(). When I do so (I call "blocking.interrupt()"), nothing happens... no exception is thrown.. it just silently fails.
    Ok, so I suppose that we can not interrupt a remote thread.. that is fine. But what if I want to interrupt the RMI thread making the remote call? I don't want it to block forever. How can I "cancel" the remote call?
    Ideally, I would like the remote.blockingMethod() call to throw an InterruptException when I issue an "interrupt()" on the blocking thread. Any suggestions on how I might accomplish this?
    Thanks,
    Bryan

    While you can interrupt the RMI call, you cannot stop the active processing. That is, you cannot force a thread to stop (see the Java API documentation on Thread.stop().)
    Since the Client RMI call is a waiting thread, you need another Client thread to do a secondary RMI call. The trick is to have the new RMI endpoint connection thread on the RMI Server interrupt the original RMI endpoint connection thread.
    The only way you can interrupt an RMI call is to have the endpoint connection thread that runs on the RMI Server be aware that the user may wish to interrupt it.
    The best means of interruption is for the endpoint connection thread to use "worker threads". The endpoint connection thread waits for the workers to finish and is interruptible by both the workers and other endpoint connection threads.
    Another means of interruption is for the endpoint connection thread to segment the task into units of work and check for an interruption between those units of work.
    There are two ways I've done RMI call interruption.
    One is for the Client to pass a unique id (UID -- that uniquely identifies the request) to the Server with the original call. When the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread.
    The major problem with this is the unique id. It absolutely, positively must be unique. Otherwise you run the risk of Client_A purging Client_B's request.
    The second method requires callback. If your Client is behind a firewall then RMI callback is near impossible. In such a case you must come up with a way for the Server to call the Client that is secure (the firewall problem.)
    The Client must export a remote object and pass that remote object to the Server with the original call.
    The endpoint connection thread recognizes the remote object and does a call back to the Client passing information that uniquely identifies itself (UID). Since the Server generates the UID, it can guarantee uniqueness.
    The Client callback implementation runs as a separate thread since the Client is in fact an RMI Server itself (when it did the export.) The Client must save the UID. The Client must start a new thread for the interrupt procedure or inform a waiting thread that the Server called back.
    Just like method one, above, when the Client wishes to interrupt the original call, using the separate thread, it does a new RMI call to the Server passing the UID.
    The new endpoint connection thread, using the UID, interrupts the original endpoint connection thread. Simple.
    For an academic example using call back go over to Jini.org. They have an example called "Cancellation" at:
    http://starterkit-examples.jini.org/
    For a professional, open source implementation of both these methods go over to CoopSoft.com. The Tymeac (Java) projects support canceling both waiting and autonomous requests at:
    http://www.coopsoft.com/JavaProduct.html

  • How to restart an interrupted thread ?

    Hi All,
    I have to stop a thread and then restart it after sometime. Since, stop() method is deprecated in jdk1.3 so, I m using interrupt() instead of stop() method. Can anyone please tell me , what does interrupting a thread exactly means? Does it termainates a thread completely or not?
    Because , if I use thread.interrupt() and then thread.start() just after it, it raises exception java.lang.IllegalThreadStateException but still starts the thread.
    Prime concern is how to stop and restart a thread without using stop() method??
    Thanx and regards,
    Shweta

    You have to determine in the run method if the thread has been interrupted.
    Usually like this
    run()
    while(!isInterrupted())
    // code body
    you could try this
    boolean restart;
    run()
    while (true)
    if (isInterrupted())
    waitForRestart();
    // code
    waitForRestart()
    restart = false;
    while (!restart)
    sleep(500);
    restart(){restart = true;}

  • Interrupting a Thread thats blocking for I/O

    OK, here is the problem. I need to interrrupt a thread that is blocking on I/O. The run method of my thread looks something like this...
    run(){
    while(connected){
    try{
    recieved = in.readLine();
    // do something with recieved data
    } catch(InterruptedIOException e){
    // do something
    } catch(SocketException e){
    // do something else
    } catch(IOException e){
    // do some more of something else
    I also have a fuction like this...
    private void stop(){
    connected = false;
    myThread.interrupt();
    None of this appears to be working. The interrup method runs but no exceptions are thrown. I need to be able to tell the thread to stop blocking for I/O an stop running. Is there some other way, or am I on the right track and its just coded wrong? Any help would be great.

    There are 2 reasons for your code to mallfunction:
    1. You should catch an InterruptedException first (this is thrown at Thread.interrupt()), not InterruptedIOException (which comes from the Socket).
    2. For ensuring your thread.stop, you have messed up 2 different techniques:
    Setting the connected = false in your stop method could make you jump out your whole while loop, so you will never reach you code in the catch blocks.
    You also call myThread.interrupt() so if you stop() method occurs in the middle of processing, you will end-up in you catch(InterruptedException) block.
    So there are 2 distinct reactions that may occur at your stop(), depending on them moment when it is called, which doesn't look so good.
    Depending on how you want your code to behave (to end-up in the catch block or after the whole while loop) use just one of the instructions in your stop() method. It is recomended that you keep 'connected = false', but then you have to watch out the blocking IORead :(

  • Threading Issue, not being interrupted

    Apparently I suck with threading. Take for example, this method.
    public Thread process()
                   return new Thread(){
              public void run()
                   while(!Thread.interrupted())
                       try {
                             Thread.sleep(500);
                             display.asyncExec(new Runnable() {
                                  public void run() { 
                                       pb.notifyListeners(SWT.Modify, new Event()); 
                        } catch (InterruptedException e) {
                             try {
                                  Thread.currentThread().join();
                             } catch (InterruptedException e1) {
                                  // TODO Auto-generated catch block
                                  e1.printStackTrace();
                             e.printStackTrace();
              }When I attempt to do process().start(); the thread will kick off, but when I do process().interrupt(); the thread doesn't stop. No matter what I do i can't seem to stop the thread.

    I just noticed that I am attempting to interrupt a different thread than I started, because everytime I call the method it returns a different thread. Teaches me to copy and paste code...
    Thread t = process();
    t.start();
    t.interrupt();Edited by: sarcasteak on Oct 15, 2009 1:36 PM

  • Thread doesn't return control to main() after being interrupted, why?

    Hello,
    From the following code you would expect control returned to main() after a thread is interrupted. But output shows otherwise. Why?
    Thank you in advance for your help!
    public class HelloRunnableInterruptB implements Runnable {
         public void run() {
              System.out.println("Hello from a thread!");
              while (true) {
                   if (Thread.interrupted()) {
                        System.out.println("Interrupt received in infinite loop");
                        return;
         public static void main(String[] args) {
              HelloRunnableInterruptB threadObj = new HelloRunnableInterruptB();
              Thread thread1 = new Thread(threadObj);
              thread1.start();
              thread1.interrupt();
              System.out.println("main: 1st statement after interrupt()");
    /*Output:
    Hello from a thread!
    Interrupt received in infinite loop
    */

    From the following code you would expect control returned to main() after a thread is interrupted. But output shows otherwise. Why?No. It is giving result as expected. Thread dies when its run() method complete execution.
    Moreover, when you call a start() method , the result is that two threads runs concurrently: the main thread and the other thread. They have two different lines of execution.

  • Running thread behaviour on calling interrupt?

    if a thread T1 is running and interrupt is called on this thread,there will be no impact on thread T1 processing/behaviour. To handle this
    we have to call if (Thread.interrupted()) inside run method of thread T1 right?
    Interrupt will have impact when thread is under wait,sleep or join(or methods that throw InterruptedException),Right?
    In above question , impact refers to the case when InterruptedException will be thrown.
    Asked the question at http://www.coderanch.com/t/545582/threads/java/Impact-interrupt-Running-thread but did not get satisfactory reply though i have been thru api doc.

    Interrupting a thread sets a flag for that thread. Setting that flag will cause some blocking operations to throw an exception. e.g. sleep, wait, NIO read. Unless you do one of those operations, setting the flag doesn't do anything which is a problem for those who hope to stop a running thread in an untrusted third party library. ;)

  • Timer that will interrupt a thread

    How do I create a timer that will interrupt a thread?
    I need to put this timer inside the thread, and I should be able to manipulate the time.
    I have managed to create an inner class that act as the timer. But, I can't make the timer to interrupt the main thread.
    Can anyone help me? Is there any simpler way to do this?

    See Thread.interrupt()
    If you call this while a thread has called sleep() and is waiting, this should then throw an InterruptedException
    BTW, in the case where you have a thread that reading from a socket / inputstream, and blocked on read(), the way that I always use to unblock my thread is to simply close the stream, which generates an IOException and unblocks the thread.
    ...And BTW Thread.stop() has never been implemented and does nothing!
    Edited by: tjacobs01 on Jan 3, 2008 6:09 AM

  • Interrupting Main Thread

    Hi,
    Is there a way to interrupt a Thread.sleep() (ie the main Thread executing)
    I was also wondering if when you call Thread.enumerate() if
    it returns an array of all the new threads which have been created and still exist at that point in time ?
    The reason is, sometimes after a period of time after my application has been running, and 'rdate' will happen on the system and if the time is set backwards, any Threads currently sleeping do not wake up and need to be interrupted.

    Did you look at the API docs?
    Thread.interrupt() will interrupt a Thread. You could
    keep a reference to all your sleeping threads and call
    interrupt() on each one when you want. This will
    interrupt them from their "sleep" and throw an
    InterruptedException.
    http://java.sun.com/j2se/1.3/docs/api/java/lang/Thread.
    tml
    http://java.sun.com/j2se/1.3/docs/api/java/lang/Interru
    tedException.htmlYes, I do understand how interrupt will interrupt a thread from a sleep. I should rephrase the question - There are currently a number of threads executing (there are over 2000 classes). This particular class does not know anything about the threads executing and their current state. When the system time is changed (by an rdate (unix)) this class is notified by a C program (which calls the rdate). Any threads in a sleep at this current time will come out of the sleep because time has gone backwards - so now the currentTimeMillies is returning a value less than the time it started the sleep with. Now ... I need to interrupt all of the threads which are currently sleeping - which this class does not have a handle to, it is only for being notified when an 'rdate' happens. I have worked out, I can use Thread.enumerate(Thread [] threads) to get a handle to all of the current threads. I can interrupt all of the threads by looping through this array. What I was asking is ... If a class uses a Thread.sleep - so it is telling the main thread to sleep - how do I interrupt it (I have worked out the enumerate() call will even return the AWT thread, so I assume I can interrupt it)
    Now another problem is, the interrupt will not interrupt threads which are currently in a wait() state.

Maybe you are looking for

  • TS1398 my iphone 4s used to connect to wifi now it wont

    my iphone 4s used to connect to wifi now all of a sudden it wont and i havent changed any settings can anyone help?

  • Oracle Business Intelligence (OBIEE) Keeps Kicking Me Out

    Im quite confused about what is going on with OBIEE. I have a DEV, QA and PROD enviroment. In both DEV and PROD I can log in to OBIEE, navigate around no problem. When I go into QA then everytime I click on a report link or navigate anywhere it const

  • Regarding Report writer

    Hi, can anyone of u please let me know how to create a report writer and report painter. if possible please send me the step by step method of creation . Thanks & Regards, lavanya.

  • Ipod wont connect to wifi, says "unable to join the network"

    my ipod touch wont allow me to join my home wifi network, tells me "unable to join the network"

  • MIDI CLICK TRACK?

    hey guys I notice the MIDI CLICK at the bottom of my track list, how can i activate it? Pretty much, i want an audible MIDI/Metronome click for this project. Im trying to make a backing track. Left channel will be a click with the backing tracks, rig