interrupt中断线程问题
来源:8-9 interrupt函数
慕粉302336
2019-02-23
课程中有讲到,interrupt方法会中断处于阻塞状态的线程,并使线程该线程抛出IterruptedException异常。但是程序Demo中线程t1调用 sleep方法使线程进入等待状态,并非阻塞状态,也出现了线程中断和IterruptedException异常。
interrupt方法是否也会终止处于等待状态的线程??
2回答
-
同学好,sleep方法会使线程进入阻塞状态,而非等待状态。。。
1)sleep 休眠方法:
Static void sleep(long ms)
该方法会使当前线程进入阻塞状态指定毫秒,当阻塞指定毫秒后,当前线程会重新进入Runnable状态,等待划分时间片。
2)wait方法一般是跟notify方法连用的:
多线程之间需要协调工作。如果条件不满足则等待。当条件满足时,等待该条件的线程将被唤醒。在Java中,这个机制实现依赖于wait/notify。
interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态,具体还需要程序去控制。
012019-02-24 -
翔仔
2019-02-24
同学好,不好意思,由于市面出现两套不同的状态描述,也许会让同学混淆概念了,同学可以忽视我昨晚短路给的回复,咱们直接通过源码来分析。
/** * Thread state for a thread blocked waiting for a monitor lock. * A thread in the blocked state is waiting for a monitor lock * to enter a synchronized block/method or * reenter a synchronized block/method after calling * {@link Object#wait() Object.wait}. */ BLOCKED, /** * Thread state for a waiting thread. * A thread is in the waiting state due to calling one of the * following methods: * <ul> * <li>{@link Object#wait() Object.wait} with no timeout</li> * <li>{@link #join() Thread.join} with no timeout</li> * <li>{@link LockSupport#park() LockSupport.park}</li> * </ul> * * <p>A thread in the waiting state is waiting for another thread to * perform a particular action. * * For example, a thread that has called {@code Object.wait()} * on an object is waiting for another thread to call * {@code Object.notify()} or {@code Object.notifyAll()} on * that object. A thread that has called {@code Thread.join()} * is waiting for a specified thread to terminate. */ WAITING, /** * Thread state for a waiting thread with a specified waiting time. * A thread is in the timed waiting state due to calling one of * the following methods with a specified positive waiting time: * <ul> * <li>{@link #sleep Thread.sleep}</li> * <li>{@link Object#wait(long) Object.wait} with timeout</li> * <li>{@link #join(long) Thread.join} with timeout</li> * <li>{@link LockSupport#parkNanos LockSupport.parkNanos}</li> * <li>{@link LockSupport#parkUntil LockSupport.parkUntil}</li> * </ul> */ TIMED_WAITING,
也就是说,当调用Sleep的时候,线程是处于限期等待状态的。
但是这里需要区分的是,当调用wait的时候,线程会放弃已经获得的锁进入等待池,之后如果正常的话又会进入到锁池,所以这个是池的概念,而非状态概念。
抛InterruptedException的代表方法有:
1. java.lang.Object 类的 wait 方法
2. java.lang.Thread 类的 sleep 方法
3. java.lang.Thread 类的 join 方法
也就是说不管是sleep还是wait方法,调用interrupt的时候,都有可能会抛InterruptedException这个异常,但interrupt方法并不是强制终止线程,它只能设置线程的interrupted状态,具体还需要程序去控制。
00
相似问题
回答 2
回答 1