interrupt()、 isInterrupted() 、static interrupted()
+ interrupt()方法是告诉线程需要中断一些,但是是否会中断由线程自身决定。所以一般结合isInterrupted() 、static interrupted()2个方法一起使用。
+ isInterrupted() 返回当前线程的中断状态,不会重置线程的中断状态。
+ static interrupted() 返回当前线程的中断状态,并且会重置isInterrupted()为false
在sleep(),wait()等方法都会抛出一个InterruptedException,这时候捕获这个异常的时候,要主动重新调用interrupt()方法。否则可能无法正确中断线程。
线程之间的共享
synchronized内置锁
volatile 关键字
线程间的协作
wait() notify() notifyAll()
sleep() yield()
join()
面试点:线程A执行了县城B的join方法,那么线程A必须等到线程B执行以后,线程A才会继续自己的工作。
wait() notify() yield() sleep()对锁的影响
面试点:
线程执行yield(),线程让出cpu执行时间,和其他线程同时竞争cup执行机会,但如果持有的锁不释放。
线程执行sleep(),线程让出cpu执行时间,在sleep()醒来前都不竞争cpu执行时间,但如果持有的锁不释放。
notify调用前必须持有锁,调用notify方法本身不会释放锁。
wait()方法调用前必须持有锁,调用了wait方法之后,锁就会被释放。当wait方法返回的时候,线程会重新持有锁。