活锁出现在两个线程互相改变对方的结束条件,最后谁也无法结束,例如

    1. public class TestLiveLock {
    2. static volatile int count = 10;
    3. static final Object lock = new Object();
    4. public static void main(String[] args) {
    5. new Thread(()->{
    6. //期望减到0退出循环
    7. while (count>0){
    8. try {
    9. Thread.sleep(200);
    10. } catch (InterruptedException e) {
    11. e.printStackTrace();
    12. }
    13. count--;
    14. System.out.println("count:{}"+count);
    15. }
    16. },"t1").start();
    17. new Thread(()->{
    18. //期望超过20退出循环
    19. while (count<20){
    20. try {
    21. Thread.sleep(200);
    22. } catch (InterruptedException e) {
    23. e.printStackTrace();
    24. }
    25. count++;
    26. System.out.println("count:{}"+count);
    27. }
    28. },"t2").start();
    29. }
    30. }

    虽然没有死锁的真正加锁(即synchronized操作),但是两个线程确实无法结束,出现的效果如下:
    image.png