读书人

Thread.interrupt() 怎么使用

发布时间: 2012-12-28 10:29:05 作者: rapoo

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");}}

读书人网 >编程

热点推荐