分享
 
 
 

java thread programming 1.5 - Gracefully Stopping Threads

王朝java/jsp·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

interrupt()

While one thread is running, another thread can interrupt it by invoking its corresponding Thread object’s interrupt() method:

public void interrupt()

This method simply sets a flag in the destination thread indicating that it has been interrupted and returns right away. It is possible that a SecurityException will be thrown by interrupt(), indicating that the thread requesting the interrupt does not have permission to interrupt the other thread. The security check is done by invoking the checkAccess() method on Thread, which in turn checks whether a SecurityManager has been installed, and if so, invokes its checkAccess(Thread) method. An in-depth exploration of security in Java is beyond the scope of this book, but you should note that some methods of Thread and ThreadGroup could throw SecurityExceptions.

本方法修改线程标志位表明线程已经中断,立刻返回,在某些安全要求比较高的环境(applet)如果存在SecuityManager可能会抛出SecurityException异常。

isInterrupted()

You can check the interrupted status of any thread by invoking the isInterrupted() method on the Thread object:

public boolean isInterrupted()

This does not alter the status, but simply returns true if the thread has been interrupted and its interrupted flag has not yet been cleared.

探测线程是否中断,本函数执行完毕,中断标志位不被清除

Thread.interrupted()

You can use the Thread.interrupted() method to check (and implicitly reset to false) the interrupted status of the current thread:

public static boolean interrupted()

Because it is static, it cannot be invoked on a particular thread, but can only report the interrupted status of the thread that invoked it. This method returns true if the thread has been interrupted and its interrupted flag has not yet been cleared. Unlike isInterrupted(), it automatically resets the interrupted flag to false. Invoking Thread.interrupted() a second time would always return false unless the thread was reinterrupted. Listing 5.4 shows an example of how you can use Thread.interrupted().

探测线程是否中断,本程序执行完毕,中断标志重置为false

Deprecated Methods suspend() and resume()

The Thread API contains two deprecated methods that are used to temporarily stop and later restart a thread:

public final void suspend()

public final void resume()

Methods and classes are deprecated by Sun Microsystems to indicate that developers should avoid using them. A deprecated method can still be used, but when the code is compiled, a warning is issued. Deprecation is used to indicate a method or class is obsolete or dangerous and may be removed from future releases of the JDK. Although you may still use deprecated methods, you should use them sparingly and only when absolutely necessary.

suspend()挂起线程

resume()恢复线程执行

@Deprecation 表明此方法不推荐使用,在jdk将来版本可能会被剔出

The suspend() method is deprecated as of JDK 1.2 because if a thread is suspended at an inopportune time—such as when it is holding a lock for a shared resource—a deadlock condition may result. I explain and demonstrate deadlocks in Chapter 7, “Concurrent Access to Objects and Variables,” but let it suffice to say for now that a deadlock is a very bad thing and can cause a program to freeze up on a user. Even when locks are not involved, a thread might be suspended while in the middle of a long procedure that really should not be left in a partially completed state. The resume() method is deprecated because without any use of suspend(), it is not needed.

不推荐使用suspend()的原因:

1、 当线程占有某些共享资源时,将其挂起,很容易造成死锁,

2、 当执行某些不能被部分完成的大操作时,线程可能会被挂起

不推荐使用resume()的原因是因为不推荐使用suspend()

Deprecated Method stop()

At times, one of the additional threads spawned in a multithreaded program is no longer needed, but it continues to execute statements—perhaps in an infinite loop. The Thread API includes a stop() method to abruptly terminate a thread’s execution:

public final void stop()

When this method is invoked on a thread, the thread immediately throws a java.lang.ThreadDeath error (a subclass of java.lang.Error, which itself is a subclass of java.lang.Throwable). This exception propagates up the method call stack, executing any finally clauses present and releasing any locks that are currently held. Ultimately, this exception causes run() to abruptly return, and the thread dies.

调用stop()方法时,线程会立刻抛出ThreadDeath error(java.lang.Error的子类,java.lang.Error本身是java.lang.Throwable的子类),线程会释放所有锁,run()立刻返回,线程死亡

The stop() method is deprecated as of JDK 1.2 because it can lead to corrupted data in objects. One problem is that when a thread is stopped abruptly, there is little opportunity to perform any cleanup work. Another problem is that when stop() is invoked on a thread, the thread releases all the locks it is currently holding. The locks are definitely being held for a good reason—probably to keep other threads from accessing data elements that are not yet in a consistent state. This sudden release of the locks may leave some data in some objects in an inconsistent state with no warning about the possible corruption. In many cases, there are other ways to have a thread return from run() in an orderly manner that leaves all objects in a consistent state.

stop被取消的原因:

1、 当一个线程被粗暴中止,可能还没有进行清除工作

2、 锁机制就是防止访问共同资源其他线程处于不连续状态,线程被stop之后,会释放其拥有所有锁,造成其它线程不连续

An Alternative to stop():变通方法

AlternateStop.java源码

/*

* Created on 2005-7-8

*

* Java Thread Programming - Paul Hyde

* Copyright ? 1999 Sams Publishing

* Jonathan Q. Bo 学习笔记

*

*/

package org.tju.msnrl.jonathan.thread.chapter1;

/**

* @author Jonathan Q. Bo from TJU MSNRL

*

* Email:jonathan.q.bo@gmail.com

* Blog:blog.csdn.net/jonathan_q_bo

* blog.yesky.net/jonathanundersun

*

* Enjoy Life with Sun!

*

*/

public class AlternateStop implements Runnable {

private Thread runThread;

private volatile boolean stopRequest;

/*

* @see java.lang.Runnable#run()

*/

public void run() {

this.runThread = Thread.currentThread();

stopRequest = false;

int counter = 0;

while(!stopRequest){

System.out.println("running ... ... count = " + counter);

counter++;

try{

Thread.sleep(300);

}catch(InterruptedException e){

Thread.currentThread().interrupt();

}

}

}

public void stopThread(){

this.stopRequest = true;

if(this.runThread != null){

this.runThread.interrupt();

}

}

public static void main(String[] args) {

AlternateStop at = new AlternateStop();

Thread newThread = new Thread(at);

newThread.start();

try{

Thread.sleep(2000);

}catch(InterruptedException e){

System.out.println(e.getMessage());

}

at.stopThread();

}

}

Daemon Threads

Threads that are marked as daemons stop in a whole new way. Daemon threads are used for background supporting tasks and are only needed while normal, nondaemon threads are still running. When the VM detects that the only remaining threads are daemon threads, it exits. If any nondaemon thread is still alive, the VM will not exit. Daemon threads provide a nice way of managing some sort of behind-the-scenes processing that is only necessary to support other nondaemon threads.

守护线程:当其他通常的非守护线程运行时,后台执行;当其他线程结束,剩下的都是守护线程时,虚拟机停止守护线程。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
 
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有