Java多线程 中断机制及实例详解
正文
这里详细分析interrupt(),interrupted(),isInterrupted()三个方法
interrupt()
中断这个线程,设置中断标识位
publicvoidinterrupt(){
if(this!=Thread.currentThread())
checkAccess();
synchronized(blockerLock){
Interruptibleb=blocker;
if(b!=null){
interrupt0();//Justtosettheinterruptflag
b.interrupt(this);
return;
}
}
interrupt0();
}
我们来找下如何设置中断标识位的
找到interrupt0()的源码,src/hotspot/share/prims/jvm.cpp
JVM_ENTRY(void,JVM_Interrupt(JNIEnv*env,jobjectjthread))
...
if(is_alive){
//jthreadreferstoaliveJavaThread.
Thread::interrupt(receiver);
}
JVM_END
调用了Thread::interrupt方法
src/hotspot/share/runtime/thread.cpp
voidThread::interrupt(Thread*thread){
...
os::interrupt(thread);
}
os::interrupt方法,src/hotspot/os/posix/os_posix.cpp
voidos::interrupt(Thread*thread){
...
OSThread*osthread=thread->osthread();
if(!osthread->interrupted()){
//设置中断标识位
osthread->set_interrupted(true);
...
}
...
}
isInterrupted()
测试线程是否被中断,线程的中断状态不会改变
publicbooleanisInterrupted(){
returnisInterrupted(false);
}
查看nativeisInterrupted(booleanClearInterrupted)源码,查找方式同上
src/hotspot/os/posix/os_posix.cpp
boolos::is_interrupted(Thread*thread,boolclear_interrupted){
debug_only(Thread::check_for_dangling_thread_pointer(thread);)
OSThread*osthread=thread->osthread();
//查看是否被中断
boolinterrupted=osthread->interrupted();
//清除标识位后再设置false
if(interrupted&&clear_interrupted){
osthread->set_interrupted(false);
}
returninterrupted;
}
Java传递ClearInterrupted为false,对应C++的clear_interrupted
interrupted()
测试线程是否被中断,清除中断标识位
publicstaticbooleaninterrupted(){
returncurrentThread().isInterrupted(true);
}
简单的例子
publicclassMyThread45{
publicstaticvoidmain(String[]args)throwsException
{
Runnablerunnable=newRunnable()
{
publicvoidrun()
{
while(true)
{
if(Thread.currentThread().isInterrupted())
{
System.out.println("线程被中断了");
return;
}
else
{
System.out.println("线程没有被中断");
}
}
}
};
Threadt=newThread(runnable);
t.start();
Thread.sleep(500);
t.interrupt();
System.out.println("线程中断了,程序到这里了");
}
}
检查线程是否中断,中断线程,运行结果如下
······ 线程没有被中断 线程没有被中断 线程没有被中断 线程被中断了 线程中断了,程序到这里了
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。