[Future]
Http://www.gznc.edu.cn/yxsz/jjglxy/book/Java_api/java/util/concurrent/Future.html
[Curious]
(1) What is the internal implementation of future. Cancel (mayinterruptifrunning? It can interrupt the "that" task being executed in a thread pool.
It can be guessed that the specific thread ID must be recorded and an interrupt signal is sent.
(2) It is suggested that only an interrupt signal can be sent to interrupt the operation in blocking. If it is a while (true); the non-blocking operations that occupy the CPU are not interrupted, that is, the thread is still running, occupying the thread pool resources.
Note]
A) The thread pool resources are limited. Some tasks will not be submit () and an exception is thrown: Java. util. Concurrent. rejectedexecutionexception
B) as long as the submit () succeeds, whether the thread is being executed or waiting for execution in blockingqueue, the future. Cancel () operation can interrupt the thread. That is, it has nothing to do with its actual execution. Blocking or waiting for scheduled execution will be interrupted.
[Demo]
Future. Cancel:
public class Main {
/** Semaphore */
private Semaphore semaphore = new Semaphore(0); // 1
/** Thread pool */
private ThreadPoolExecutor pool = new ThreadPoolExecutor(3, 5, 3, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(3));
/** Future */
private Future<String> future ;
public void test(){
future = pool.submit(new Callable<String>() {
@Override
public String call() {
String result = null;
try {
// Obtain the semaphore through synchronous Blocking
semaphore.acquire();
result = "ok";
} catch (InterruptedException e) {
result = "interrupted";
}
return result;
}
});
String result = "timeout";
try {
// Wait 3 S
result = future.get(3, TimeUnit.SECONDS);
}catch (Exception e) {
System. Out. println ("timeout exception ");
}
// Delete tasks in the thread pool
boolean cancelResult = future.cancel(true);
System.out.println("result is " + result);
System. Out. println ("delete Result:" + cancelresult );
System. Out. println ("current number of active threads:" + pool. getactivecount ());
}
public static void main(String[] args) {
Main o = new Main();
o.test();
}
}