Java 多线程编程之 interruptException

下面是java 多线程中的异常处理:


package multithread;

public class InterruptException {

	public static void main(String[] args) throws InterruptedException {
		Thread thread1 = new InterruptThread1();
		
		Thread thread2 = new InterruptThread2();
		thread1.start();
		thread2.start();
		
		Thread.sleep(1000);
		thread1.interrupt();
		
		Thread.sleep(1000);
		
		thread2.interrupt();
	}

	private static class InterruptThread1 extends Thread {
		public void run() {
			while (!Thread.currentThread().isInterrupted()) {
				try {
					Thread.sleep(100);
					System.out.println("running 1");
				} catch (InterruptedException e) {
					System.out.println("InterruptedException 1");
					Thread.currentThread().interrupt();
				}
			}
		}
	}

	private static class InterruptThread2 extends Thread {
		public void run() {
			try {
				while (!Thread.currentThread().isInterrupted()) {
					Thread.sleep(100);
					System.out.println("running 2");
				}
			} catch (InterruptedException e) {
				System.out.println("InterruptedException 2");
				Thread.currentThread().interrupt();
			}
		}
	}
}

猜你喜欢

转载自daojin.iteye.com/blog/2391945