这是一个模拟猴子拿苹果的问题,我们可以使用Java的面向对象编程来解决。首先,我们需要定义一个Monkey
类,表示每只猴子。然后,我们使用多线程来模拟两只猴子拿苹果的过程。
下面是一个简单的实现:
java复制代码
import java.util.concurrent.atomic.AtomicInteger; | |
class Monkey { | |
private String name; | |
private AtomicInteger appleCount; | |
public Monkey(String name) { | |
this.name = name; | |
this.appleCount = new AtomicInteger(0); | |
} | |
public void pickApple(int numApples) { | |
while (true) { | |
int currentCount = appleCount.get(); | |
if (currentCount >= numApples) { | |
appleCount.addAndGet(-numApples); | |
return; | |
} else { | |
int newCount = currentCount + numApples; | |
if (appleCount.compareAndSet(currentCount, newCount)) { | |
return; | |
} | |
} | |
} | |
} | |
public int getAppleCount() { | |
return appleCount.get(); | |
} | |
@Override | |
public String toString() { | |
return "Monkey " + name + ": " + appleCount; | |
} | |
} | |
public class Main { | |
public static void main(String[] args) throws InterruptedException { | |
Monkey monkey1 = new Monkey("Monkey 1"); | |
Monkey monkey2 = new Monkey("Monkey 2"); | |
int totalApples = 100; | |
int applesPerMonkey = totalApples / 2; // 让两只猴子拿的苹果数量接近,这里假设总苹果数是100,所以每只猴子拿50个。 | |
new Thread(() -> monkey1.pickApple(applesPerMonkey)).start(); | |
new Thread(() -> monkey2.pickApple(applesPerMonkey)).start(); | |
while (monkey1.getAppleCount() < applesPerMonkey || monkey2.getAppleCount() < applesPerMonkey) { | |
Thread.sleep(100); // 等待一段时间,确保两只猴子都拿到了足够的苹果。 | |
} | |
System.out.println(monkey1 + ", " + monkey2); // 输出每只猴子的苹果数量。 | |
} | |
} |
在这个代码中,我们创建了两个Monkey
对象,并使用多线程模拟了它们拿苹果的过程。每个猴子每次尝试拿一定数量的苹果,如果成功则返回,否则继续尝试。主线程会等待直到每只猴子都拿到了足够的苹果数量。