Java Thread Stop方法以及替换实现
来源:互联网 发布:身份鉴权超时cms 编辑:程序博客网 时间:2024/05/22 20:29
http://blog.csdn.net/longronglin/article/details/3408510
Stop方法不推荐使用,我给个具体的例子:
- public class DeprecatedStop extends Object implements Runnable {
- public void run() {
- int count = 0;
- while ( count <20 ) {
- System.out.println("Running ... count=" + count);
- count++;
- try {
- Thread.sleep(300);
- } catch ( InterruptedException x ) {
- // ignores
- }
- }
- // the code maybe not executed
- System.out.println("stoped");
- }
- public static void main(String[] args) {
- DeprecatedStop ds = new DeprecatedStop();
- Thread t = new Thread(ds);
- t.start();
- try {
- Thread.sleep(2000);
- } catch ( InterruptedException x ) {
- // ignore
- }
- // Abruptly stop the other thread in its tracks!
- t.stop();
- }
- }
可能的运行结果:
- Running ... count=0
- Running ... count=1
- Running ... count=2
- Running ... count=3
- Running ... count=4
- Running ... count=5
- Running ... count=6
可以发现程序中的打印stoped并没有执行,所以说如果在程序中有其他操作,如果线程突然stop是会带来严重的影响的。所以怎么也应该使用该操作。当然如果是我上面的程序代码突然stop的影响其实是没有的,但是如果是其他打开文件最后需要释放或者什么的就会带来严重的影响了。
如何在程序中对其进行停止呢?
- public class AlternateStop extends Object implements Runnable {
- private volatile boolean stopRequested;
- private Thread runThread;
- public void run() {
- runThread = Thread.currentThread();
- stopRequested = false;
- int count = 0;
- while ( !stopRequested ) {
- System.out.println("Running ... count=" + count);
- count++;
- try {
- Thread.sleep(300);
- } catch ( InterruptedException x ) {
- Thread.currentThread().interrupt(); // re-assert interrupt
- }
- }
- System.out.println("stoped");
- }
- public void stopRequest() {
- stopRequested = true;
- if ( runThread != null ) {
- runThread.interrupt();
- }
- }
- public static void main(String[] args) {
- AlternateStop as = new AlternateStop();
- Thread t = new Thread(as);
- t.start();
- try {
- Thread.sleep(2000);
- } catch ( InterruptedException x ) {
- // ignore
- }
- as.stopRequest();
- }
- }
可能的运行结果如下:
- Running ... count=0
- Running ... count=1
- Running ... count=2
- Running ... count=3
- Running ... count=4
- Running ... count=5
- Running ... count=6
- stoped
这样我们就解决了强制 stop的问题。
0 0
- Java Thread Stop方法以及替换实现
- Java Thread Stop方法以及替换实现
- Java Thread Stop方法以及替换实现
- Java Thread Stop方法以及替换实现
- Java学习 - Thread的Stop方法以及替换实现
- Java中的线程Thread方法之---stop()
- java stop thread
- java中俩种方法实现一个线程,以及不推荐使用stop()和suspend()方法
- Thread中的stop方法过时
- 为什么Thread.stop()方法被弃用
- java如何正确停止Thread,thread.stop ?
- 为什么不能使用Thread.stop()方法?
- Thread的Suspend和Stop方法
- 为什么不能使用Thread.stop()方法?
- Thread.stop()
- Java - Start and Stop a Thread
- 《综》Java Thread - stop 问题 and 解决方法
- java thread的stop,suspend,resume等方法废弃的原因
- oracle jdeveloper 代码智能提示+字体+编码 配置方法
- c#params应用
- 机房收费系统——MDI窗体与子窗体问题
- java synchronized
- Cxf Webservice安全认证
- Java Thread Stop方法以及替换实现
- 完全卸载oracle11g步骤
- Drawable资源(包含shape)
- ios7自带的晃动效果
- 子线程如何获取和设置 或者控制窗口实时显示数据(网上的资料经个人整理拼凑总结)
- 多校联盟--20140801--G - Christmas Play
- Linux自学路线图
- hash是如何处理冲突的?
- 二叉树镜像