import java.util.concurrent.Callable ;
import java.util.concurrent.FutureTask ;
import java.util.concurrent.TimeUnit ;
public class Main {
public static void main
( String [ ] args
) { //GOAL: make "cancel(true)" interrupt the thread that calls get()
// a task that just blocks and sets the interrupted flag
final FutureTask< Void> task = new FutureTask<> ( new Callable< Void> ( ) {
@Override
try {
} finally {
// the interrupted flag must be set manually to carry through
Thread .
currentThread ( ) .
interrupt ( ) ; }
return null ;
}
} ) ;
// a different thread to cancel above task, since this thread will be
// blocked by executing avove task.
public void run( ) {
try {
task.cancel ( true ) ;
}
} .start ( ) ;
// task executed in local thread
task.run ( ) ;
// both task & this thread should be interrupted now:
System .
out .
println ( "This thread interrupted? " + Thread .
currentThread ( ) .
isInterrupted ( ) ) ;
try {
task.get ( 1 , TimeUnit.MINUTES ) ;
e.printStackTrace ( ) ;
}
}
}
aW1wb3J0IGphdmEudXRpbC5jb25jdXJyZW50LkNhbGxhYmxlOwppbXBvcnQgamF2YS51dGlsLmNvbmN1cnJlbnQuRnV0dXJlVGFzazsKaW1wb3J0IGphdmEudXRpbC5jb25jdXJyZW50LlRpbWVVbml0OwoKcHVibGljIGNsYXNzIE1haW4gewoKICAgIHB1YmxpYyBzdGF0aWMgdm9pZCBtYWluKFN0cmluZ1tdIGFyZ3MpIHsKICAgIAkvL0dPQUw6IG1ha2UgImNhbmNlbCh0cnVlKSIgaW50ZXJydXB0IHRoZSB0aHJlYWQgdGhhdCBjYWxscyBnZXQoKQoKICAgICAgICAvLyBhIHRhc2sgdGhhdCBqdXN0IGJsb2NrcyBhbmQgc2V0cyB0aGUgaW50ZXJydXB0ZWQgZmxhZwogICAgICAgIGZpbmFsIEZ1dHVyZVRhc2s8Vm9pZD4gdGFzayA9IG5ldyBGdXR1cmVUYXNrPD4obmV3IENhbGxhYmxlPFZvaWQ+KCkgewogICAgICAgICAgICBAT3ZlcnJpZGUKICAgICAgICAgICAgcHVibGljIFZvaWQgY2FsbCgpIHRocm93cyBFeGNlcHRpb24gewogICAgICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgICAgICBUaHJlYWQuc2xlZXAoTG9uZy5NQVhfVkFMVUUpOwogICAgICAgICAgICAgICAgfSBmaW5hbGx5IHsKICAgICAgICAgICAgICAgIAkvLyB0aGUgaW50ZXJydXB0ZWQgZmxhZyBtdXN0IGJlIHNldCBtYW51YWxseSB0byBjYXJyeSB0aHJvdWdoCiAgICAgICAgICAgICAgICAgICAgVGhyZWFkLmN1cnJlbnRUaHJlYWQoKS5pbnRlcnJ1cHQoKTsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIHJldHVybiBudWxsOwogICAgICAgICAgICB9CiAgICAgICAgfSk7CgogICAgICAgIC8vIGEgZGlmZmVyZW50IHRocmVhZCB0byBjYW5jZWwgYWJvdmUgdGFzaywgc2luY2UgdGhpcyB0aHJlYWQgd2lsbCBiZQogICAgICAgIC8vIGJsb2NrZWQgYnkgZXhlY3V0aW5nIGF2b3ZlIHRhc2suCiAgICAgICAgbmV3IFRocmVhZCgpIHsKICAgICAgICAgICAgcHVibGljIHZvaWQgcnVuKCkgewogICAgICAgICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgICAgICAgICBUaHJlYWQuc2xlZXAoMTAwMCk7CiAgICAgICAgICAgICAgICB9IGNhdGNoIChFeGNlcHRpb24gZSkge30KICAgICAgICAgICAgICAgIHRhc2suY2FuY2VsKHRydWUpOwogICAgICAgICAgICB9CiAgICAgICAgfS5zdGFydCgpOwoKICAgICAgICAvLyB0YXNrIGV4ZWN1dGVkIGluIGxvY2FsIHRocmVhZAogICAgICAgIHRhc2sucnVuKCk7CgogICAgICAgIC8vIGJvdGggdGFzayAmIHRoaXMgdGhyZWFkIHNob3VsZCBiZSBpbnRlcnJ1cHRlZCBub3c6CiAgICAgICAgU3lzdGVtLm91dC5wcmludGxuKCJUaGlzIHRocmVhZCBpbnRlcnJ1cHRlZD8gIiArIFRocmVhZC5jdXJyZW50VGhyZWFkKCkuaXNJbnRlcnJ1cHRlZCgpKTsKCiAgICAgICAgdHJ5IHsKICAgICAgICAgICAgdGFzay5nZXQoMSwgVGltZVVuaXQuTUlOVVRFUyk7CiAgICAgICAgfSBjYXRjaCAoRXhjZXB0aW9uIGUpIHsKICAgICAgICAgICAgZS5wcmludFN0YWNrVHJhY2UoKTsKICAgICAgICB9CiAgICB9Cn0K