[JAVA concurrent programming practices] 6. Interrupt and java concurrent programming practices
The so-called interrupt operation: it does not actually interrupt a running thread, but only sends an interrupt request, and then the thread interrupts itself at the next appropriate time.
Call an interrupt to interrupt the request. The call is to restore the interrupt status.
1. Response interruption
Handle interrupt exceptions:
1. Transmission exception
2. Restore the interrupted state
Here is an example for running a task in a limited time. No matter whether the program responds to the terminated program or does not respond to the interrupted program within the specified time, we can all get results by calling this method,
That is to say, you can get the processing result within the specified time, and then you can define how the result is processed.
Package cn. study. concurrency; import java. util. concurrent. executors; import java. util. concurrent. scheduledExecutorService; import java. util. concurrent. timeUnit;/***** @ author xiaof **/public class TimeCount {private static final ScheduledExecutorService cancelExec = Executors. newSingleThreadScheduledExecutor ();/***** @ param r thread * @ param timeout task timeout limit * @ param unit time unit * @ throws Throwable */pu Blic static void timedRun (final Runnable r, long timeout, TimeUnit unit) throws Throwable {class RethrowableTask implements Runnable {// thrown exception private volatile Throwable t; @ Override public void run () {try {r. run ();} catch (Throwable e) {this. t = e ;}}/*** when the operation times out or the program Exits normally, call this method later for control and return it to the caller * @ throws Throwable */void rethrow () throws Throwable {// This t can be wrapped by itself or other data is returned, this can be determined based on different services. // This You can even keep the current status to the local machine. During the next running, read the local data and restore it to the current status. if (t! = Null) throw t ;}} RethrowableTask task = new RethrowableTask (); final Thread taskThread = new Thread (task); taskThread. start (); // start the External Thread cancelExec. schedule (new Runnable () {public void run () {// startup interrupt exception taskThread. interrupt () ;}}, timeout, unit); // wait for the termination of the thread to deal with the task, even if the task does not respond to the interruption, the time is limited to one, the caller taskThread still can throw an exception to this method. join (unit. toMillis (timeout); // throw an exception task. rethrow ();}}