producerConsumer
Thu Jan 18 2024 18:12:02 GMT+0000 (Coordinated Universal Time)
Saved by
@login
public class Queue{
private boolean Vset=false;
private int n;
public synchronized void get() throws Exception{
while(!Vset){
wait();
}
System.out.println("Got:"+n);
Vset=false;
notify();
}
public synchronized void put(int n)throws Exception{
while (Vset) {
wait();
}
this.n=n;
System.out.println("Put:"+n);
Vset=true;
notify();
}
}
public class ThreadService {
public static Runnable getProducer(Queue q){
return new Runnable() {
private Queue queue=q;
int i=1;
public void run(){
while (true) {
try{
queue .put(i++);
}catch(Exception e){
e.printStackTrace();
}
}
}
};
}
public static Runnable getConsumer(Queue q){
return new Runnable() {
private Queue queue=q;
public void run(){
while (true) {
try{
queue.get();
}catch(Exception e){
e.printStackTrace();
}
}
}
};
}
}
public class ProducerConsumerDemo {
public static void main(String[] args) {
Queue q=new Queue();
new Thread(ThreadService.getProducer(q)).start();
new Thread(ThreadService.getConsumer(q)).start();
}
}
content_copyCOPY
Comments