您的位置:首页 > 编程语言 > Java开发

Java_Thread_interrupt中断线程

2014-10-27 10:57 537 查看
一直以来都有一个错误的理解,认为调用了interrupt()方法就会中断线程,但事实上并非如此,调用一个线程的interrupt方法会把线程的状态改为中断态,但是interrupt方法只作用于那些因为执行了sleep、wait、join方法而休眠的线程,使他们不再休眠,同时会抛出InterruptedException异常。
比如一个线程A正在sleep中,这时候另外一个程序里去调用A的interrupt方法,这时就会迫使A停止休眠而抛出InterruptedException异常;而如果线程A没有处于上面提到的三种休眠状态时被interrupt,这样就只是把线程A的状态改为interrupted,但是不会影响线程A的继续执行。
/**
* Interrupts this thread.
*
* <p> Unless the current thread is interrupting itself, which is
* always permitted, the {@link #checkAccess() checkAccess} method
* of this thread is invoked, which may cause a {@link
* SecurityException} to be thrown.
*
* <p> If this thread is blocked in an invocation of the {@link
* Object#wait() wait()}, {@link Object#wait(long) wait(long)}, or {@link
* Object#wait(long, int) wait(long, int)} methods of the {@link Object}
* class, or of the {@link #join()}, {@link #join(long)}, {@link
* #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},
* methods of this class, then its interrupt status will be cleared and it
* will receive an {@link InterruptedException}.
*
* <p> If this thread is blocked in an I/O operation upon an {@link
* java.nio.channels.InterruptibleChannel </code>interruptible
* channel<code>} then the channel will be closed, the thread's interrupt
* status will be set, and the thread will receive a {@link
* java.nio.channels.ClosedByInterruptException}.
*
* <p> If this thread is blocked in a {@link java.nio.channels.Selector}
* then the thread's interrupt status will be set and it will return
* immediately from the selection operation, possibly with a non-zero
* value, just as if the selector's {@link
* java.nio.channels.Selector#wakeup wakeup} method were invoked.
*
* <p> If none of the previous conditions hold then this thread's interrupt
* status will be set. </p>
*
* <p> Interrupting a thread that is not alive need not have any effect.
*
* @throws SecurityException
* if the current thread cannot modify this thread
*
* @revised 6.0
* @spec JSR-51
*/
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();

synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}//关于Thread.join()用法
public static void main(String[] args) {
Thread subThread = new Thread() {
public void run() {
try {
System.out.println("sub Thread doing...");
sleep(5000);
System.out.println("sub Thread done!");
} catch (InterruptedException e) {
e.printStackTrace();
}
};
};
subThread.start();

System.out.println("main Thread doing...");
try {
System.out.println("main Thread ---->waiting");
subThread.join();// /当前线程阻塞,知直到subThread执行完。
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("main Thread done!");
}

// sub Thread doing...
// main Thread doing...
// main Thread ---->waiting
// sub Thread done!
// main Thread done!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: