正 文

中断JAVA线程


www.7dspace.com  更新日期:2006-1-27 8:07:35  七度空间


如果你运行了Listing A中的代码,你将在控制台看到以下输出:

Starting thread...

Thread is running...

Thread is running...

Thread is running...

Interrupting thread...

Thread is running...

Thread is running...

Thread is running...

Stopping application...

甚至,在Thread.interrupt()被调用后,线程仍然继续运行了一段时间。

真正地中断一个线程

中断线程最好的,最受推荐的方式是,使用共享变量(shared variable)发出信号,告诉线程必须停止正在运行的任务。线程必须周期性的核查这一变量(尤其在冗余操作期间),然后有秩序地中止任务。Listing B描述了这一方式。

Listing B

class Example2 extends Thread {

  volatile boolean stop = false;

  public static void main( String args[] ) throws Exception {

    Example2 thread = new Example2();

   System.out.println( "Starting thread..." );

   thread.start();

   Thread.sleep( 3000 );

   System.out.println( "Asking thread to stop..." );

   thread.stop = true;

   Thread.sleep( 3000 );

   System.out.println( "Stopping application..." );

   System.exit( 0 );

  }

  public void run() {

    while ( !stop ) {

     System.out.println( "Thread is running..." );

      long time = System.currentTimeMillis();

      while ( (System.currentTimeMillis()-time < 1000) && (!stop) ) {

      }

    }

   System.out.println( "Thread exiting under request..." );

  }

}

5页,页码:[1] [2] [3] [4] [5] 

上一篇:java.util.concurrent工具
下一篇:企业机架式服务器:1U还是2U
标题:中断JAVA线程 作者: 来源:开发者在线
收藏此页】【打印】【关闭
站 内 搜 索
 

热 点 导 读
特 别 推 荐