Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

multithreading - How to stop all runnable thread in java executor class?

final ExecutorService executor = Executors.newFixedThreadPool(1);
final Future<?> future = executor.submit(myRunnable);
executor.shutdown();
if(executor.awaitTermination(10, TimeUnit.SECONDS)) {
  System.out.println("task completed");
}else{
  System.out.println("Executor is shutdown now");
}

//MyRunnable method is defined as task which I want to execute in a different thread.

Here is run method of executor class:

public void run() {
try {
     Thread.sleep(20 * 1000);
} catch (InterruptedException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
}}

Here it is waiting for 20 second but when i run the code it throws an exception:

java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)

I am not able to close the concurrent thread ruining in Java Executor class. Here is my Code flow:

  • Created a new Thread with Java executor class to run some task i.e written in MyRunnable
  • executor wait for 10 second to complete the tasks.
  • If the task has completed then runnable thread also got terminated.
  • If the task is not completed within 10 second then executor class should terminate the thread.

Everything works fine except the termination of tasks in the last scenario. How should I do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The shutDown() method simply prevents additional tasks from being scheduled. Instead, you could call shutDownNow() and check for thread interruption in your Runnable.

// in your Runnable...
if (Thread.interrupted()) {
  // Executor has probably asked us to stop
}

An example, based on your code, might be:

final ExecutorService executor = Executors.newFixedThreadPool(1);
executor.submit(new Runnable() {
  public void run() {
    try {
      Thread.sleep(20 * 1000);
    } catch (InterruptedException e) {
      System.out.println("Interrupted, so exiting.");
    }
  }
});

if (executor.awaitTermination(10, TimeUnit.SECONDS)) {
  System.out.println("task completed");
} else {
  System.out.println("Forcing shutdown...");
  executor.shutdownNow();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...