????????????????????????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..."??);????
本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/sanxing/article-69021-2.html
真的
开打