public class Test1 {
public static void main(String[] args) {
AppleBox ab = new AppleBox();
Producer p = new Producer(ab);
Producer p2= new Producer(ab);
Consumer c = new Consumer(ab);
Thread t = new Thread(p);
t.setName("生產者一*****");
t.start();
Thread t2 = new Thread(p2);
t2.setName("生產者二&&&&&");
t2.start();
Thread t3 = new Thread(c);
t3.setName("消費一#####");
t3.start();
}
}
class Producer implements Runnable {
AppleBox appleBox;
public Producer(AppleBox appleBox) {
this.appleBox = appleBox;
}
@Override
public void run() {
// 生產10個蘋果存到appleBox中
for (int i = 0; i < 5; i++) {
Apple a = new Apple(i);
appleBox.deposite(a);
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Consumer implements Runnable {
AppleBox appleBox;
public Consumer(AppleBox appleBox) {
this.appleBox = appleBox;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
Apple a = appleBox.withdraw();
try {
Thread.sleep((int) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class AppleBox {
int index = 0;
Apple[] apples = new Apple[5];
public synchronized void deposite(Apple apple) {
// 判斷apples是否滿了,滿了,則不能再存
while(index >= apples.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
apples[index] = apple;
index++;
System.out.println(Thread.currentThread().getName()+"生產了"+apple);
// 沒滿,就存
this.notifyAll();
}
public synchronized Apple withdraw() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Apple a = apples[index - 1];
index--;
this.notifyAll();
System.out.println(Thread.currentThread().getName()+"消費了"+a);
return a;
}
}
class Apple {
int id;
Apple(int id) {
this.id = id;
}
public String toString() {
return "apple " + id;
}
}
輸出結果:
生產者一*****生產了apple 0
消費一#####消費了apple 0
生產者二&&&&&生產了apple 0
消費一#####消費了apple 0
生產者二&&&&&生產了apple 1
生產者一*****生產了apple 1
生產者二&&&&&生產了apple 2
消費一#####消費了apple 2
消費一#####消費了apple 1
生產者二&&&&&生產了apple 3
生產者一*****生產了apple 2
生產者一*****生產了apple 3
消費一#####消費了apple 3
生產者一*****生產了apple 4
生產者二&&&&&生產了apple 4
消費一#####消費了apple 4
消費一#####消費了apple 4
消費一#####消費了apple 2
消費一#####消費了apple 3
消費一#####消費了apple 1
輸出結果第五行第六行都生產了apple1
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/184807.html
標籤:Java相關
上一篇:Idea啟動時報錯
