java多线程
2017-09-21 本文已影响0人
文艺小年青
生产者与消费者问题
package xianPack;
//生产者 消费者
public class Test10 {
public static void main(String[] args) {
final Apple apple = new Apple();
//吃苹果的人 (上下两种方法一样)
new Thread(new Runnable() {
public void run() {
try {
apple.eat();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"线程1").start();
Thread thread1 = new Thread(new Runnable() {
public void run() {
try {
apple.eat();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"线程2");
thread1.start();
//种苹果的
new Thread(new Runnable() {
public void run() {
try {
apple.plant();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},"线程3").start();
new Thread(new Runnable() {
public void run() {
try {
apple.plant();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},"线程4").start();
}
}
class Apple {
int num = 0; //苹果的数量
//吃苹果
void eat() throws InterruptedException {
while (true) {
synchronized (this) {
if (num > 0) {
num--;
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + "吃苹果,剩下" + num);
//并且通知种苹果的种
notifyAll();
}else { //没有苹果了
//进入等待状态
wait();
//并且通知种苹果的种
//notify(); //通知一个
}
}
}
}
//种苹果
void plant() throws InterruptedException {
while (true) {
//锁放在里边 一边吃一边种
synchronized (this) {
//如果生产大于20个,停止生产
if (num < 20) {
this.num++;
Thread thread = Thread.currentThread();
System.err.println(thread.getName() + "种苹果,剩下" + num);
//通知吃苹果的吃
notifyAll(); //通知所有的
}else { //苹果太多 不能生产了
//等待
wait();
}
}
}
}
}