Java Multithreading: Interrupting Threads (Video Tutorial Part 14)

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&lt>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

3 Responses to Java Multithreading: Interrupting Threads (Video Tutorial Part 14)

  1. Janine says:

    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 :)

  2. magesh says:

    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.

  3. Ozkan says:

    Thank you very much for such as kind great examples and really nicely explained!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Posted in Java, Java Multithreading, Java Video Tutorials (Advanced) | Tagged , , , , , |