java中线程的状态包括“新建状态”,”就绪状态”,”运行状态”,”阻塞状态”以及”死亡状态”.
下面是java的状态变化图
1.新建状态:线程被创建后进进入了新建状态Thread t=new Thread().
2.就绪状态:线程调用start()方法启动线程就进入了就绪状态,又被称为可执行状态.
3.运行状态:线程获取CPU执行,就由就绪状态进入了运行状态。
4.阻塞状态:因某些原因造成线程放弃cpu执行权,就由运行状态转换为阻塞状态,
这些原因可能是线程调用join/wait/sleep/yield方法,也可能是线程在获取synchronized同步锁失败(被其他线程占用)造成的阻塞。阻塞状态解除后就会进入就绪状态
5.死亡状态:当线程的run方法执行完毕,线程的状态就由运行状态转变为死亡状态.
Thread类执行interrupt()方法,下面是JDK1.8的源码
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
nativeInterrupt();
b.interrupt(this);
return;
}
}
nativeInterrupt();
}
public static native boolean interrupted();//返回"当前线程”的中断状态,并且随后会将中断状态标志清除。
public native boolean isInterrupted();//仅仅是获取线程当前是否是中断状态
interrupt方法调用会中断线程,线程状态会被置为”中断”标志,但是中断线程并不会造成停止线程的执行,只是仅仅会把线程状态置为”中断”.当线程在执行阻塞操作时(比如调用sleep/wait/yield/join方法时)调用了interrupt()会抛出InterruptException异常并且将该线程的”中断”标志位清空,会将线程的中断标志重新设置为false.
class MyThread implements Runnable{
@Override
public void run() {
try {
Thread.sleep(3000);
}catch (InterruptedException e){
System.out.println(Thread.currentThread().getName()+" appear InterruptedException:isInterrupted="+Thread.currentThread().isInterrupted());//返回false,验证抛出InterruptException异常后“中断”状态标志被清除.
}
System.out.println(Thread.currentThread().getName()+":Thread.interrupted="+Thread.interrupted());//这个还会打印出来表示线程虽然调用了中断操作但并不能停止线程运行。
}
}
@Test
public void testInterrupt(){
Thread thread=new Thread(new MyThread());
thread.start();
try {
System.out.println(Thread.currentThread().getName()+"11111111");
Thread.sleep(1000);
System.out.println(Thread.currentThread().getName()+"22222222");
thread.interrupt();//执行中断线程操作
}catch (InterruptedException e){
}
System.out.println(Thread.currentThread().getName()+"3333333333");
}