Javamex

Java discussion forum to accompany the Javamex web site.

Hi All,

I am new at implementing Producer Consumer problem, although the program runs good. I had a question on results of (Bold print statement below) , it's always true meaning the queue is empty prior to take()

Can anyone help me with this? Is there a way to find if the queue is populated at the Consumer thread?

TIA

Anjana.

package trail;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;

class MyProducer implements Runnable{
int m=0;
String[] S ={"dog","cat"};
String[] S2 = {"bark","meow"};
String K1="d";

MyProducer(int k, String[] S1){
m=k;
S=S;
}

@SuppressWarnings("empty-statement")
public void run()
{
for (int i=0; i<15; i++)
{
m=2*i;
S = S; //{"dog","cat"};
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Logger.getLogger(MyProducer.class.getName()).log(Level.SEVERE, null, ex);
}
Main.queue.add(S);
System.out.println("P"+Main.queue.isEmpty());
System.out.println("Inserting "+ i);
S =S2;
}
}
}



class MyConsumer implements Runnable {


private boolean done=false;
public void run()
{
while (done==false)
{
try
{
System.out.println("C"+Main.queue.isEmpty());
String[] K = Main.queue.take();

for (int z=0; z< K.length;z++){
//System.out.println("Consuming number " + Main.queue.take()[z]);
System.out.println("Consuming number " + K[z]);
}
Thread.sleep(50);

}catch(InterruptedException ex)
{
System.out.println("Tired, exiting now");
done = true;
}

}
}

}

public class Main {

public static BlockingQueue queue = new ArrayBlockingQueue( 100 );
public static int col = 100;
public static void main(String[] args)
{
Main my = new Main();
String[] S2=null;
ExecutorService service = Executors.newFixedThreadPool(2);
service.execute(new MyProducer(1, S2));
service.execute(new MyConsumer());


}


}

Views: 66

Reply to This

© 2024   Created by Neil Coffey.   Powered by

Badges  |  Report an Issue  |  Terms of Service