首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Thread.interrupt() 怎么使用

2012-12-28 
Thread.interrupt() 如何使用今天看到一个blogger说:好记性,不如烂博客。还是蛮有道理的,踏实的记录,经常的

Thread.interrupt() 如何使用
今天看到一个blogger说:好记性,不如烂博客。
还是蛮有道理的,踏实的记录,经常的回顾。
写blog贵在坚持写和常回来看看。
言归正传,今天研究了一下Thread.interrupt()方法,这个方法很有意思,Thread.interrupt()的调用对正在运行的线程是不起作用的,只有对阻塞的线程有效。
   public class CountupThread extends Thread{private long counter=0;private volatile boolean shutdownRequests=false;public void shutdownRequest(){shutdownRequests=true;interrupt();}public final void run(){try {while (!shutdownRequests) {doWork();}} catch (InterruptedException e) {e.printStackTrace();}finally{doShutdown();}}private void doWork() throws InterruptedException{counter++;System.out.println("doWork:counter="+counter);Thread.sleep(500);}private void doShutdown(){System.out.println("doShutdown:counter="+counter);}}

public class Main {/** * @param args */public static void main(String[] args) {System.out.println("Main:begin");CountupThread t=new CountupThread();try {t.start();Thread.sleep(10000);System.out.println("Main:shutDownRequest");t.shutdownRequest();System.out.println("Main:join");t.join();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(t.isAlive());System.out.println("Main:end");}}

热点排行