Solved

Multithreading

Posted on 2004-08-19
9
260 Views
Last Modified: 2010-03-31
I have a helper class , whose method i invoke . The problem is that method can take upto 15 sec to finish. But i only want to wait 10 sec...if it doesnt return in 10 sec...i would like to kill that method call.


I am thinking i have to spawn new threads...one for the method call...another to keep track of time.....
Can someone tell me how to accomplish this.
Pappu
0
Comment
Question by:rahulkothari
  • 2
  • 2
  • 2
  • +3
9 Comments
 
LVL 35

Accepted Solution

by:
TimYates earned 125 total points
ID: 11841557
Does:

   thread.join( 10000 ) ;
   if( thread.isAlive() )
        thread.interrupt() ;

work?
0
 
LVL 3

Expert Comment

by:JohnnyAffa
ID: 11841583
use the javax.swing.Timer

Timer timer = new Timer([int delay], [ActionListener al]);
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11842503
what do you mean by "kill"? What is the helper method doing for the 15 seconds? It might be likely that that task might not be capable of being stopped, in which case you'll just have to ignore it, and continue as if its not running (if you have control of the code, it might be possible to put in code that will allow it to be stopped (e.g. a "stillRunning" boolean method checked in a loop, if there is a loop, or if its IO, the stream might be closable, etc... really depends on what is going on in the helper method...
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rahulkothari
ID: 11842762
I did it something like this :

***************************
import java.util.*;

class test1 extends Thread
{
      public void run(){
            for (int i=0;i<=6 ;i++ )
            {
                  System.out.println("Sleeping "+ i + " second.");
                              try {
                                          long numMillisecondsToSleep = 1000; // 1 second
                                          Thread.sleep(numMillisecondsToSleep);
                                    } catch (InterruptedException e) {
                                          System.out.println("INTERUPTED");
                                          return;
                                    }
            }
      }
}

public class Test
{
      public Test(){
             try
             {
             Thread thread = new test1();
         thread.start();
             Thread.sleep(10000);
             if(thread.isAlive())thread.interrupt() ;
             }
             catch (Exception e)
             {
                   e.printStackTrace();
             }

      }
      
      public static void main(String[] args)
      {
            new Test();
      }
}
*****************************


But in this case i always sleep for 10 sec.....as you can see my sample test1 thread finishes in 6 sec......how do i avoid sleeping for that extra 4 sec in case my helper thread finishes before 10 sec. ???

Please suggest
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11842857
>> Thread.sleep(10000);

Make that a call to wait () instead of sleep ().

In the run () method, make a call to notifyAll (). Better to put it in a finally block so that it gets executed even when there is an exception and you're returning.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11842982
Use join instead of sleep (like I suggested)
0
 
LVL 11

Expert Comment

by:cjjclifford
ID: 11843025
Hi,

Just to follow on from before, using "thread.interrupt()" is fine if the helper method is waiting or sleeping, - if the interrupt() is called while the other thread is working, e.g. performing some labourous processing task, the interrupt is likely not to do anything...

A test will show this:

public class Test {
    public static void main( String[] args ) throws Exception {
        Thread testthread = new Thread(
            new Runnable() {
                public void run() {
                    // dumbly spin on a counter, to simulate a busy processing task...
                    for( long i = 0; i != 1000000000; i++ ) {}
                    System.out.println( "Finished stupidly spinning" );
                    synchronized( this ) {
                        notifyAll();
                    }
                }
            } );

        System.out.println( "Starting test thread" );
        testthread.start();
        System.out.println( "Waiting for a short while!" );
        Thread.sleep( 100 );
        System.out.println( "interrupting testthread" );
        testthread.interrupt();
        System.out.println( "After the interrupt" );
        synchronized( testthread ) {
            testthread.wait();
        }
    }
}

In this case, the way around it is to provide a object boolean "stillRunning", and set it to false instead of the interrupt() - also, this boolean would have to be in the loop conditional...

As I said before, really dependant on the type of processing being done in the thread.... If you can give an idea of what is being done, a way of interrupting/abandoning it should be devisable...

Cheers,
C.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 11843032
Ah, yes. join ( int ) is better.
0
 
LVL 4

Expert Comment

by:bhpr
ID: 11849986
What about this:

public class Test
{
     public Test(){
           try
           {
           Thread thread = new test1();
                  thread.start();
           //Thread.sleep(10000);
               mysleep(1000,10,thread);
           if(thread.isAlive())thread.interrupt() ;
           }
           catch (Exception e)
           {
                e.printStackTrace();
           }

     }

       private void mysleep (int msbreaksups, int times, Thread _thread) {
            while (thread.isAlive() && times > 0) {
                  try      {
                              Thread.sleep(msbreakups);
                  } catch (Exception e)      {
                        e.printStackTrace();
                  }
                  times--;
            }
       }
     
     public static void main(String[] args)
     {
          new Test();
     }
}

bhpr
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

680 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question