Good example of livelock?

后端 未结 11 1744
后悔当初
后悔当初 2021-01-29 18:44

I understand what livelock is, but I was wondering if anyone had a good code-based example of it? And by code-based, I do not mean \"two people trying to get p

11条回答
  •  深忆病人
    2021-01-29 18:49

    package concurrently.deadlock;
    
    import static java.lang.System.out;
    
    
    /* This is an example of livelock */
    public class Dinner {
    
        public static void main(String[] args) {
            Spoon spoon = new Spoon();
            Dish dish = new Dish();
    
            new Thread(new Husband(spoon, dish)).start();
            new Thread(new Wife(spoon, dish)).start();
        }
    }
    
    
    class Spoon {
        boolean isLocked;
    }
    
    class Dish {
        boolean isLocked;
    }
    
    class Husband implements Runnable {
    
        Spoon spoon;
        Dish dish;
    
        Husband(Spoon spoon, Dish dish) {
            this.spoon = spoon;
            this.dish = dish;
        }
    
        @Override
        public void run() {
    
            while (true) {
                synchronized (spoon) {
                    spoon.isLocked = true;
                    out.println("husband get spoon");
                    try { Thread.sleep(2000); } catch (InterruptedException e) {}
    
                    if (dish.isLocked == true) {
                        spoon.isLocked = false; // give away spoon
                        out.println("husband pass away spoon");
                        continue;
                    }
                    synchronized (dish) {
                        dish.isLocked = true;
                        out.println("Husband is eating!");
    
                    }
                    dish.isLocked = false;
                }
                spoon.isLocked = false;
            }
        }
    }
    
    class Wife implements Runnable {
    
        Spoon spoon;
        Dish dish;
    
        Wife(Spoon spoon, Dish dish) {
            this.spoon = spoon;
            this.dish = dish;
        }
    
        @Override
        public void run() {
            while (true) {
                synchronized (dish) {
                    dish.isLocked = true;
                    out.println("wife get dish");
                    try { Thread.sleep(2000); } catch (InterruptedException e) {}
    
                    if (spoon.isLocked == true) {
                        dish.isLocked = false; // give away dish
                        out.println("wife pass away dish");
                        continue;
                    }
                    synchronized (spoon) {
                        spoon.isLocked = true;
                        out.println("Wife is eating!");
    
                    }
                    spoon.isLocked = false;
                }
                dish.isLocked = false;
            }
        }
    }
    

提交回复
热议问题