0

I happened to come across this article for killing a thread after some time using the Executor service : Killing thread after some specified time limit in Java

This is the code mentioned in the article :

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.invokeAll(Arrays.asList(new Task()), 10, TimeUnit.MINUTES); // Timeout of 10 minutes.
executor.shutdown();

Now that I have a runnable thread to be executed in my program .How do I kill this thread after some time using the above mentioned code?

Here's a part of my code which I have used for creating threads :

public static List<Thread> thread_starter(List<Thread> threads,String filename)
{   String text=read_from_temp(filename);
     Runnable task = new MyRunnable(text);
     Thread worker = new Thread(task);  
     worker.start();
      // Remember the thread for later usage
     threads.add(worker);
    return threads;
}

public class MyRunnable implements Runnable {
MyRunnable(String text)
{ 
this.text=text;
}
@Override
public void run() {
  /* other computation*/
}

I create multiple threads by calling thread_started() function .

Can anyone please help me on combining Executor Service with it . I tried a lot but couldn't find any way out !

Community
  • 1
  • 1
kiran
  • 339
  • 4
  • 18
  • may be you should look at this answer... http://stackoverflow.com/a/15900500/614868 –  Feb 24 '14 at 06:06

1 Answers1

1

In java, you can NOT kill a running thread directly. If you want to kill your running thread, you need a running flag in your task, check it in thread task, and set it outside. Eg:

   MyRunnable task = ....;
   ......
   task.running = false;  //stop one task


   public class MyRunnable implements Runnable {
       public boolean running = true;
       public void run() {
            while(running){
                 .....
            }
       }

What you mentioned 'ExecutorService' is single thread 'ExecutorService', it would exec tasks one by one, what it do for timeout is just waiting a task completed and calculate/compare each task's time with timeout. You can find it in java's source code 'AbstractExecutorService.java'.

yinqiwen
  • 604
  • 6
  • 6