b2科目四模拟试题多少题驾考考爆了怎么补救
b2科目四模拟试题多少题 驾考考爆了怎么补救

java版本 停止Java线程,小心interrupt()方法(2)

电脑杂谈  发布时间:2018-02-09 15:33:02  来源:网络整理

????????????????????????while((System.currentTimeMillis()-time??<??1000))??{????

????????????????????????}????

????????????????????????}????

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

????????????????????????}????

????????????????????????}????

如果你运行了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 is running...??

Thread is running...??

Thread is running...??

...............................??

甚至,在Thread.interrupt()被调用后,线程仍然继续运行。??

真正地中断一个线程??

?????? 中断线程最好的,最受推荐的方式是,使用共享变量(shared variable)发出信号,告诉线程必须停止正在运行的任务。java版本线程必须周期性的核查这一变量(尤其在冗余操作期间),然后有秩序地中止任务。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..."??);????


本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/sanxing/article-69021-2.html

相关阅读
    发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

    • 李纾
      李纾

      看了你这么多文字

    • 雷冰
      雷冰

      没有一发炮弹击穿主装甲

    • 胡传美
      胡传美

      不过这样的军事表演秀是不会起到任何作用的

    热点图片
    拼命载入中...