62,614
社区成员
发帖
与我相关
我的任务
分享
package entity;
public class Apple {
public Integer num = 0;
public void addApple() {
synchronized (num) {
while (num == 5) {
try {
num.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num++;
System.out.println(Thread.currentThread().getName() + "添加苹果" + " "
+ "苹果数量" + num);
num.notifyAll();
}
}
public void getApple() {
synchronized (num) {
while (num == 0) {
try {
num.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
num--;
System.out.println(Thread.currentThread().getName() + "取走苹果" + " "
+ "苹果数量" + num);
num.notifyAll();
}
}
}
package xiancheng;
import entity.Apple;
public class Add implements Runnable {
public Apple apple;
public Add(){}
public Add(Apple apple){
this.apple=apple;
}
@Override
public void run() {
// TODO Auto-generated method stub
apple.addApple();
}
}
package xiancheng;
import entity.Apple;
public class Min implements Runnable {
public Apple apple;
public Min(){}
public Min(Apple apple){
this.apple=apple;
}
@Override
public void run() {
// TODO Auto-generated method stub
apple.getApple();
}
}
package xiancheng;
import entity.Apple;
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Apple apple = new Apple();
Add add = new Add(apple);
Min min = new Min(apple);
new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(add).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();
new Thread(min).start();
}
}