kiran
kiran

Reputation: 349

Using Executor & Runnable together to kill threads after some time

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 !

Upvotes: 0

Views: 974

Answers (1)

yinqiwen
yinqiwen

Reputation: 659

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'.

Upvotes: 1

Related Questions