同学好,不好意思,由于市面出现两套不同的状态描述,也许会让同学混淆概念了,同学可以忽视我昨晚短路给的回复,咱们直接通过源码来分析。
/**
* 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状态,具体还需要程序去控制。