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

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

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

Listing D??

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

class??Example4??extends??Thread??{????

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

????????Example4??thread??=??new??Example4();????

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

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

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

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

java最新版本是多少_对应java版本_java版本

??????thread.interrupt();????

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

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

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

????}????

????

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

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

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

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

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

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

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

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

????????while??(??true??)??{????

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

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

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

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

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

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

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

????}????

}????

??很幸运,Java平台为这种情形提供了一项解决方案,即调用阻塞该线程的套接字的close()方法。在这种情形下,如果线程被I/O操作阻塞,该线程将接收到一个SocketException异常,这与使用interrupt()方法引起一个InterruptedException异常被抛出非常相似。??

唯一要说明的是,必须存在socket的引用(reference),只有这样close()方法才能被调用。这意味着socket对象必须被共享。Listing E描述了这一情形。运行逻辑和以前的示例是相同的。??

Listing E??

import??java.net.*;????


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

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

    • 山口太郎
      山口太郎

      这蛆培养的这么肥

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