-
Thread.sleep(500);
当前线程在cpu中睡个500ms,让给别的线程去运行。sleep完回到就绪状态 -
Thread.yield();
让出cpu一会,返回就绪状态,放入等待队列中,下一个执行的线程可能是别的线程,也有可能还是自己。 -
join();
比如有2个线程t1
,t2
,在t1
内调用了t2.join();
那么从这点开始t1
要等t2
运行完,才能继续执行。
sleep(),wait(),join()在执行过程中都能被interrupt,中断标志设置为true,若是有捕获InterruptedException,在异常中自己处理。捕获到这个异常然后这个异常抛出之后,又会马上将线程中断标识重置为false。
public class TestInterrupt {
public static void main(String[] args){
Thread thread = new Thread(() -> {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println();
System.out.println("end.....");
});
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread.isInterrupted());
thread.interrupt();
System.out.println(thread.isInterrupted());
}
}
执行后输出:
false
false
end.....
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.mashibing.mytest.TestInterrupt.lambda$main$0(TestInterrupt.java:11)
at java.lang.Thread.run(Thread.java:748)
网友评论