SORU
24 HAZİRAN 2009, ÇARŞAMBA


Livelock iyi örnek?

Livelock ne olduğunu anlıyorum ama eğer herkes kod tabanlı iyi bir örnek oldu mu acaba? Ve kod tabanlı, demek istemiyorum "bir koridorda iki insan birbirini atlatmaya çalışan". Eğer tekrar okudum, öğle yemeğimi kaybederim.

CEVAP
14 Ocak 2012, CUMARTESİ


İşte karı koca çorbası, ama sadece bir kaşık çalıştığı livelock çok basit bir Java örnek. Her eşin çok kibar. ve eğer diğeri de henüz yemek yemiş değilse kaşık geçecek.

public class Livelock {
    static class Spoon {
        private Diner owner;
        public Spoon(Diner d) { owner = d; }
        public Diner getOwner() { return owner; }
        public synchronized void setOwner(Diner d) { owner = d; }
        public synchronized void use() { 
            System.out.printf("%s has eaten!", owner.name); 
        }
    }

    static class Diner {
        private String name;
        private boolean isHungry;

        public Diner(String n) { name = n; isHungry = true; }       
        public String getName() { return name; }
        public boolean isHungry() { return isHungry; }

        public void eatWith(Spoon spoon, Diner spouse) {
            while (isHungry) {
                // Don't have the spoon, so wait patiently for spouse.
                if (spoon.owner != this) {
                    try { Thread.sleep(1); } 
                    catch(InterruptedException e) { continue; }
                    continue;
                }                       

                // If spouse is hungry, insist upon passing the spoon.
                if (spouse.isHungry()) {                    
                    System.out.printf(
                        "%s: You eat first my darling %s!%n", 
                        name, spouse.getName());
                    spoon.setOwner(spouse);
                    continue;
                }

                // Spouse wasn't hungry, so finally eat
                spoon.use();
                isHungry = false;               
                System.out.printf(
                    "%s: I am stuffed, my darling %s!%n", 
                    name, spouse.getName());                
                spoon.setOwner(spouse);
            }
        }
    }

    public static void main(String[] args) {
        final Diner husband = new Diner("Bob");
        final Diner wife = new Diner("Alice");

        final Spoon s = new Spoon(husband);

        new Thread(new Runnable() { 
            public void run() { husband.eatWith(s, wife); }   
        }).start();

        new Thread(new Runnable() { 
            public void run() { wife.eatWith(s, husband); } 
        }).start();
    }
}

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Alexander Johnson

    Alexander Jo

    26 Temmuz 2008
  • MyTiredBones

    MyTiredBones

    2 Temmuz 2013
  • wafflepwn

    wafflepwn

    14 AĞUSTOS 2008