笔试,猴子吃香蕉,多线程写法

package demo;

import java.util.concurrent.CountDownLatch;

/**
 * @description: 猴子吃香蕉
 * @author: wxm
 * @create: 2023-10-23 14:01
 **/
public class Main {


    public static void main(String[] args) throws InterruptedException {
        Monkey[] m = new Monkey[3];
        Resource r = new Resource();


        for (int i = 0; i < 3; i++) {
            m[i] = new Monkey(r);
        }
        for (int i = 0; i < 3; i++) {
            int j = i;
            new Thread(()->m[j].add()).start();
        }
        r.latch.await();
        for (int i = 0; i < 3; i++) {
            System.out.println(i +" " + m[i].count);
        }
    }


}

class MyThread extends Thread{
    Monkey monkey;

    public MyThread(Monkey monkey){
        this.monkey = monkey;
    }

    @Override
    public void run(){
        monkey.add();
    }
}

class Monkey{

    Resource resource;
    int count;
    public Monkey(Resource resource){
        this.resource = resource;
        this.count = 0;
    }

    public void add(){

        try {
            while (true){
                if(resource.consumer()) count++;
                else break;
            }
        }finally {
            resource.latch.countDown();
        }

    }

}

class Resource{
    private volatile int num = 10000;
    public CountDownLatch latch = new CountDownLatch(3);
    public synchronized boolean consumer(){
        if (num == 0) return false;
        num--;
        return true;
    }

}

你可能感兴趣的:(1024程序员节)