thread interrupt
时间: 2023-10-25 15:11:16 浏览: 43
"Thread interrupt" 是指在多线程编程中,通过调用线程的 interrupt() 方法来中断该线程的执行。当线程被中断时,它会抛出一个 InterruptedException 异常,可以在 catch 块中处理该异常。
需要注意的是,interrupt() 方法并不会直接中断线程的执行,而是设置线程的中断状态为 true。线程在执行过程中可以通过检查自身的中断状态来判断是否需要中断执行。
相关问题
thread.interrupt
当一个线程处于阻塞状态(如等待锁、睡眠、等待输入/输出等)时,可以通过调用该线程的interrupt()方法来中断该线程。这会设置线程的中断标志位,但并不会立即中断线程。如果线程在等待锁,则线程依然会处于BLOCKED状态,如果线程在睡眠,则会抛出InterruptedException异常并清除中断标志位。为了保证数据的一致性和完整性,我们需要在捕获InterruptedException异常后再次中断自己,置上中断标志位。这样,线程就可以在下一次循环中检查中断标志位并退出循环。
Thread-0: started false: started Thread-0: is running Exception in thread "Thread-0" java.lang.IllegalMonitorStateException at java.base/java.lang.Object.wait(Native Method) at java.base/java.lang.Object.wait(Object.java:326) at ThreadInterrupt$1.run(ThreadInterrupt.java:11) at java.base/java.lang.Thread.run(Thread.java:835) main: stopped
这个错误是因为在线程中调用了wait()方法,但是没有获取到对象锁。wait()方法只能在synchronized块中使用,否则就会抛出IllegalMonitorStateException异常。
你可以将wait()方法调用放到synchronized块中,或者使用Lock对象来代替synchronized块。例如:
```
public void run() {
System.out.println(Thread.currentThread().getName() + ": started");
System.out.println(Thread.currentThread().isInterrupted() + ": started");
synchronized (this) {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + ": is running");
try {
wait();
} catch (InterruptedException e) {
System.out.println(Thread.currentThread().getName() + ": interrupted when sleep");
System.out.println(Thread.currentThread().isInterrupted() + ": interrupted getState()");
Thread.currentThread().interrupt();
System.out.println(Thread.currentThread().isInterrupted() + ": interrupted getState()");
}
}
}
System.out.println(Thread.currentThread().getName() + ": exiting");
}
```
这样修改后,就不会再出现IllegalMonitorStateException异常了。