多线程吃包子简单案例

Java实现多线程案例

学习内容:

需求

使用多线程实现:2个人吃包子,谁吃得多谁赢,同时记录每个人吃包子的总数量。

实现代码

public class Contest implements Runnable{
    private int count1 = 0;
    private int count2 = 0;
    private static int food = 20;
    Object ob = new Object();
    public void run() {
        while(food > 0) {
            synchronized(ob) {
                if(food > 0) {
                    try{
                        Thread.sleep(10);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "吃了第" + food + "个");
                    food--;
                    if(Thread.currentThread().getName().equals("老钟")) {
                        count1++;
                    } else {
                        count2++;
                    }
                } else {
                    if(count1 > count2) {
                        System.out.println("老钟肚子大,老钟胜出,共吃了" + count1 + "个");
                    } else if (count1 < count2) {
                        System.out.println("老李肚子大,老李胜出,共吃了" + count2 + "个");
                    } else {
                        System.out.println("平局");
                    }
                }
            }
        }
    }
}
class Test {
    public static void main(String[] args) {
        Contest contest = new Contest();
        Thread t1 = new Thread(contest, "老钟");
        Thread t2 = new Thread(contest, "老李");
        t1.start();
        t2.start();
    }
}

总结:

以上就是多线程综合案例了,代码仅供参考,欢迎讨论交流。

posted @ 2021-04-19 18:07  Yan_Yang  阅读(118)  评论(0编辑  收藏  举报