活锁出现在两个线程互相改变对方的结束条件,最后谁也无法结束,例如
public class TestLiveLock {
static volatile int count = 10;
static final Object lock = new Object();
public static void main(String[] args) {
new Thread(()->{
//期望减到0退出循环
while (count>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
System.out.println("count:{}"+count);
}
},"t1").start();
new Thread(()->{
//期望超过20退出循环
while (count<20){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
count++;
System.out.println("count:{}"+count);
}
},"t2").start();
}
}
虽然没有死锁的真正加锁(即synchronized操作),但是两个线程确实无法结束,出现的效果如下: