public class tt {
public static void main(String[] args) {
Q q = new Q();
new Thread(new Producer(q)).start();
new Thread(new Customer(q)).start();
}
}
class Producer implements Runnable{
Q q;
public Producer(Q q){this.q = q;}//
public void run() {
int i = 0;
while(true){
if(i == 0){
q.put("cup", "for drinking");
}else{
q.put("desk", "for study");
}
i = (i+1)%2;
}
}
}
class Customer implements Runnable{
Q q;
public Customer(Q q){this.q = q;}
public void run() {
while(true){
q.get();
}
}
}
class Q{
String name="unknown";
String desc="unknown";
boolean isFull = false;
public synchronized void put(String name, String desc){
if(isFull)
try {
wait();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
this.name = name;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.desc = desc;
isFull = true;
notify();
}
public synchronized void get(){
if(!isFull)
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(name);
System.out.println(":" + desc);
isFull = false;
notify();
}
}
生产者与消费者
最新推荐文章于 2011-02-22 19:37:00 发布