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

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

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

import??java.io.*;????

class??Example5??extends??Thread??{????

????volatile??boolean??stop??=??false;????

????volatile??ServerSocket??socket;????

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

????????Example5??thread??=??new??Example5();????

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

??????thread.start();????

??????Thread.sleep(??3000??);????

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

??????thread.stop??=??true;????

??????thread.socket.close();????

??????Thread.sleep(??3000??);????

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

??????//System.exit(??0??);????

????}????

????public??void??run()??{????

????????try??{????

????????????socket??=??new??ServerSocket(7856);????

????????}??catch??(??IOException??e??)??{????

??????????System.out.println(??"Could??not??create??the??socket..."??);????

????????????return;????

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

????????while??(??!stop??)??{????

??????????System.out.println(??"Waiting??for??connection..."??);????

????????????try??{????

??????????????Socket??sock??=??socket.accept();????

????????????}??catch??(??IOException??e??)??{????

????????????System.out.println(??"accept()??failed??or??interrupted..."??);????

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

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

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

????}????

}????

以下是运行Listing E中代码后的输出:??

Starting thread...??

Waiting for connection...??

Asking thread to stop...??

accept() failed or interrupted...??

Thread exiting under request...??

Stopping application...??

多线程是一个强大的工具,然而它正呈现出一系列难题。其中之一是如何中断一个正在运行的线程。如果恰当地实现,使用上述技术中断线程将比使用Java平台上已经提供的内嵌操作更为简单。


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

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

    • 朱淑真
      朱淑真

      以乱放屁罪判处3年有期徒刑

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