我正在學習使用exectorServices
來合併threads
併發出任務。下面我有在Java代碼中的executor.submit和executor.execute之間的區別?
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
class Processor implements Runnable {
private int id;
public Processor(int id) {
this.id = id;
}
public void run() {
System.out.println("Starting: " + id);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("sorry, being interupted, good bye!");
System.out.println("Interrupted "+Thread.currentThread().getName());
e.printStackTrace();
}
System.out.println("Completed: " + id);
}
}
public class ExecutorExample {
public static void main(String[] args) {
Boolean isCompleted=false;
ExecutorService executor = Executors.newFixedThreadPool(2);
for(int i=0; i<5; i++) {
executor.execute(new Processor(i));
}
//executor does not accept any more tasks but the submitted tasks continue
executor.shutdown();
System.out.println("All tasks submitted.");
try {
//wait for the exectutor to terminate normally, which will return true
//if timeout happens, returns false, but this does NOT interrupt the threads
isCompleted=executor.awaitTermination(100, TimeUnit.SECONDS);
//this will interrupt thread it manages. catch the interrupted exception in the threads
//If not, threads will run forever and executor will never be able to shutdown.
executor.shutdownNow();
} catch (InterruptedException e) {
}
if (isCompleted){
System.out.println("All tasks completed.");
}
else {
System.out.println("Timeout "+Thread.currentThread().getName());
}
}
}
一個簡單的程序,當然這並不能花哨,但創建兩個threads
和共提交5個任務。在每個thread
完成其任務後,它將採用下一個, 在上面的代碼中,我使用executor.submit
。我也改爲executor.execute
。但是我看不出輸出有什麼不同。 submit and execute
方法以何種方式不同? 這個API
說什麼
方法提交通過創建並返回一個可用於取消執行和/或等待完成的Future擴展基方法Executor.execute(一個java.lang.Runnable)。方法invokeAny和invokeAll執行最常用的批量執行形式,執行一組任務,然後等待至少一個或全部完成。 (ExecutorCompletionService類可用來編寫這些方法的自定義變體)
但它不是很清楚,我是什麼確切含義? 感謝
有用的問題。它在這裏發佈它很有價值。 – MKod