Reputation: 23
I wrote this java code with synchronized
and busy waiting
but I don't know why it doesn't work right! for example I get this output
produced:6
produced:7
consumed:0
consumed:0
how 6 and 7 are produced but 0 is consumed ??? I don't know what's wrong with it,please help me ,here is my code:
package conper;
import java.util.*;
import java.util.concurrent.TimeUnit;
class Queue<Integer> {
int items=0;
int q=0;
public int[] array= new int[10];
Queue(int i) {
}
public boolean isEmpty(){
if (this.q > 0)
{
return false ;
}else{
return true ;}
}
public boolean isFull(){
if (this.q > 10)
{
return true ;
}else{
return false ;
}
}
public int size(){
return items;
}
public synchronized void add(int x){
if(!isFull()){
array[++q]=x;
}
}
public synchronized void remove(int x){
if(!isEmpty()){
array[--q]=x;
}
}
}
class Producer implements Runnable {
private Random random = new Random();
private Queue<Integer> queue;
private boolean working = true;
public Producer(Queue<Integer> q) {
queue = q;
}
public void run() {
int product=0;
int loop = random.nextInt(10) + 20;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
while(working){
product = produce();
if(!queue.isFull() ){
break;
}
}
queue.add(product);
System.out.println("produced:"+product);
}
public void stop() {
working = false;
}
private int produce() {
int result = 0;
int loop = random.nextInt(10) + 20;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
result = random.nextInt(10);
return result;
}
}
class Consumer implements Runnable {
private Random rnd = new Random();
private Queue<Integer> queue;
private boolean working = true;
public Consumer(Queue<Integer> q) {
queue = q;
}
public void run() {
int product = 0;
while(working){
if(!queue.isEmpty())
break;
}
queue.remove(product);
System.out.println("consumed:"+product);
consume(product);
}
public void stop() {
working = false;
}
public void consume(int product) {
int loop = rnd.nextInt(10000) + 2000;
for (int i = 0; i < loop; i++) {
double h = Math.pow(2, Math.E * i);
}
}
}
public class Main {
public static void main(String[] args) {
Queue<Integer> queue = new Queue<Integer>(5);
Producer p1 = new Producer(queue);
Producer p2 = new Producer(queue);
Consumer c1 = new Consumer(queue);
Consumer c2 = new Consumer(queue);
Thread pt1 = new Thread(p1);
Thread pt2 = new Thread(p2);
Thread ct1 = new Thread(c1);
Thread ct2 = new Thread(c2);
pt1.start();
pt2.start();
ct1.start();
ct2.start();
try {
TimeUnit.MILLISECONDS.sleep(200);
p1.stop();
p2.stop();
c1.stop();
c2.stop();
}
catch (Exception e) {
return;
}
}
}
any suggestion?
Upvotes: 0
Views: 88
Reputation: 533530
Your consumer code reads
int product = 0;
// code which doesn't change "product"
System.out.println("consumed:"+product);
I suggest you need a remove() method which returns the value from the queue instead of being passed a value.
I also suggest you get the code to work in one thread before attempting to use in multiple threads.
Upvotes: 1