62,616
社区成员
发帖
与我相关
我的任务
分享
package thread;
public class ProducerAndCustomerDemo {
public static void main(String[] args) {
Queue q=new Queue();
Productor p=new Productor(q);
Customer c=new Customer(q);
p.start();
c.start();
}
}
class Customer extends Thread{
Queue q;
public Customer(Queue q) {
// TODO Auto-generated constructor stub
this.q=q;
}
@Override
public void run() {
// TODO Auto-generated method stub
while (q.value<10) {
System.out.println("Customer get "+q.get());
}
}
}
class Productor extends Thread{
Queue q;
public Productor(Queue q) {
// TODO Auto-generated constructor stub
this.q=q;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 1; i <=10; i++) {
q.put(i);
System.out.println("Productor put "+i);
}
}
}
class Queue{
int value;
boolean bFull=false;
public synchronized void put(int i){
if (!bFull) {
value=i;
bFull=true;
//notify();
notifyAll();
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public synchronized int get(){
if (!bFull) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
bFull=false;
notifyAll();
return value;
}
}