首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我们该怎么做才能克服生动活泼呢?(一般情况下和特定于下面提供的代码示例)

我们该怎么做才能克服生动活泼呢?(一般情况下和特定于下面提供的代码示例)
EN

Stack Overflow用户
提问于 2016-02-18 12:48:28
回答 1查看 738关注 0票数 0

我对Java很陌生,我正在努力学习生动活泼的概念。

我在网上发现了一个很好的例子,一对夫妻正在试着喝汤,但他们之间只有一个勺子。配偶双方都太客气了,如果对方还没吃东西,他们会把勺子递给对方的。

我的问题是,在这个特殊的例子中,我们应该做些什么来克服生动活泼的问题呢?我希望修改我的代码来演示这个问题的解决方案。

代码语言:javascript
复制
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();
    }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-18 13:07:40

一般来说,没有一个通用的方法来解决生动活泼问题。

如果没有检测到进度,则线程必须停止重复相同的操作。

在你的例子中,允许配偶多吃一次(从而发现爱人没有吃过东西,而且没有进展,因为进食只需要一步)应该迫使勺子的主人只吃一次。

很明显,现实生活中的场景会更加精细,但检测零进展和采取与通常不同的行动是至关重要的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35481945

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档