What exactly are those pesky InterruptedExceptions? In this video I show you how to interrupt running threads in Java using the built-in thread interruption mechanism.
After starting the video, click the maximise button to make it fullscreen so you can see the code!
Code For This Tutorial
Starting. Interrupted! Finished.
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class App {
public static void main(String[] args) throws InterruptedException {
System.out.println("Starting.");
ExecutorService exec = Executors.newCachedThreadPool();
Future<?> fu = exec.submit(new Callable<>Void>() {
@Override
public Void call() throws Exception {
Random ran = new Random();
for (int i = 0; i < 1E8; i++) {
if (Thread.currentThread().isInterrupted()) {
System.out.println("Interrupted!");
break;
}
Math.sin(ran.nextDouble());
}
return null;
}
});
exec.shutdown();
Thread.sleep(500);
exec.shutdownNow();
//fu.cancel(true);
exec.awaitTermination(1, TimeUnit.DAYS);
System.out.println("Finished.");
}
}
Learn to program Java Swing with my complete video course – desktop programming and applets. Includes 7 free videos. Click here for details.
All pages on this site are copyright © 2013 John W. Purcell
Thank you so much for your Multithreading Tutorials.
Great examples and really nicely explained! It helped me a lot in the start of my Concurrent Programming course.
Looking forward to more videos from you
It would be great if would demonstrate a chat application with gui(swing) and multithreading. i believe the socket code is not big here, but how they work together is what i find bit challenging.
Thank you very much for such as kind great examples and really nicely explained!