前日研究Java线程问题发现很多书上都没有提到interrput()方法提到的也说用interrupt()方法无法实现线程中断可是经过我的不断尝试竟然使用interrupt()方法和isInterrupted()方法实现了线程的中断如果这个方法可以那么除了使用共享变量的方式可以中断线程之外又多了一种中断线程的方法希望这个方法对大家有所帮助 class ThreadA extends Thread{ int count = ; public void run(){ Systemoutprintln(getName() + 将要运行); while (!thisisInterrupted()){ Systemoutprintln(getName() + 运行中 + count++); try{ Threadsleep(); // 休眠毫秒 }catch(InterruptedException e){ // 退出阻塞态时将捕获异常 Systemoutprintln(getName()+从阻塞态中退出); thisinterrupt(); // 改变线程状态使循环结束 } } Systemoutprintln(getName() + 已经终止!); } } class ThreadDemo{ public static void main(String argv[]) throws InterruptedException{ ThreadA ta = new ThreadA(); tasetName(ThreadA); tastart(); Threadsleep();// 主线程休眠毫秒等待其他线程执行 Systemoutprintln(tagetName()+ 正在被中断); tainterrupt(); // 中断线程ThreadA } } |