采用interrupt()+ 检测isInterrupted() / interrupted()异常捕获

package com;

public class MyThread extends Thread {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		super.run();
		try {
			for (int i = 0; i < 500000; i++) {
				if (this.interrupted()) {
					System.out.println("已经是停止状态了,我要退出!");
					throw new InterruptedException();
				}
				System.out.println("i=" + (i + 1));
			}
		} catch (InterruptedException e) {
			System.out.println("进MyThread.java   run 方法的catch了");
			e.printStackTrace();
		}

	}
}

  

package com;

public class Run {
public static void main(String[] args) {
	try {
		MyThread thread = new MyThread();
		thread.start();
		Thread.sleep(1000);
		thread.interrupt();
		System.out.println("是否停止1?="+thread.interrupted());
		System.out.println("是否停止1?="+thread.interrupted());
	} catch (InterruptedException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
}

  

 

posted on 2017-12-08 23:03  waytods  阅读(140)  评论(0编辑  收藏  举报