http://blog.csdn.net/wxwzy738/article/details/8516253
class Example3 extends Thread {
volatile boolean stop = false;public static void main( String args[] ) throws Exception {
Example3 thread = new Example3();
System.out.println( "Starting thread..." );
thread.start();
Thread.sleep( 3000 );
System.out.println( "Asking thread to stop..." );
thread.stop = true;//如果线程阻塞,将不会检查此变量
thread.interrupt();
Thread.sleep( 3000 );
System.out.println( "Stopping application..." );
//System.exit( 0 );
}
public void run() {
while ( !stop ) {
System.out.println( "Thread running..." );
try {//当不使用interrupt(),stop会一直等到阻塞结束才会判断,注意,interrupt()应该在阻塞前调用
Thread.sleep( 10000);//当调用interrupt(),运行到此处会直接补货异常,在一场中设置stop标志,然后while判断
} catch ( InterruptedException e ) {
System.out.println( "Thread interrupted..." );
}
}
System.out.println( "Thread exiting under request..." );
}
}