0

How do I set a time limit for a runnable thread created in Java?

There is more than 1 thread created and running at a time. How do I know the time since its creation for each thread?

This is the code I use:

List<Thread> threads = new ArrayList<Thread>();
for(int i=0;i<no_of_threads;i++){
Runnable task = new MyRunnable(text,filename,prop,filename,L,L1,seq_no);
     Thread worker = new Thread(task);  
     worker.start();
      // Remember the thread for later usage
     threads.add(worker);}


 public class MyRunnable implements Runnable {
 MyRunnable(String text,String filename,ArrayList<String> prop,String ip_file,Logger l,Logger l1,int seq_no) {
       this.text=text;
       this.filename=filename;
       this.prop=prop;
       this.ip_file=ip_file;
       this.L=l;
       this.L1=l1;
       this.seq_no=seq_no;
  }

  @Override
  public void run() {
      /* other computation*/
       }
Brett Zamir
  • 14,034
  • 6
  • 54
  • 77
kiran
  • 339
  • 4
  • 18
  • When your runnable starts running, set the start time to the current time. Inside its code, regularly check that the current time is lower then the limit added to the start time, and stop running if it's the case. – JB Nizet Feb 21 '14 at 12:38
  • This [Q&A](http://stackoverflow.com/questions/2733356/killing-thread-after-some-specified-time-limit-in-java) might be usefull. – Marco Feb 21 '14 at 12:39
  • @JBNizet : Its not possible to regularly check time because : 1. the system involves heavy computation and allotting memory for checking time is not feasible .2. When more number of threads are created , overall performance gets reduced . – kiran Feb 21 '14 at 12:44
  • 2
    System.currentTimeMillis() / System.nanoTime() don't need much memory, and they're probably fast enough. There is no other safe solution anyway. A Thread can't be stopped without its cooperation. And to cooperate, the thread has to check a condition. You could use a timer and interrupt the thread, but the interrupted thread will have to check the interrupt status regularly to know when to stop. – JB Nizet Feb 21 '14 at 12:48

1 Answers1

1

The second part is easy - just add a field startTime in your MyRunnable, as so:

public class MyRunnable implements Runnable {
  long startTime;
  ...
  public void run() {
    startTime = System.currentTimeMillis();
    ...
  }
}

For the first part, limiting running time, this is a bit more tricky. You basically need to set a timer and terminate the threads manually to do this.

Bex
  • 2,905
  • 2
  • 33
  • 36
  • Isnt there any other way of knowing time since creation for a Thread , other than computing it in the runnable method ? – kiran Feb 21 '14 at 12:47