concurrency - Java data channel implementation not correct using counting semaphore -


i try implement circle data channel communication between producer , consumer using counting semaphore, meet problems. consumed , produced data not equal.

data channel:

public class datachannel {  int[] array; int p; int c;   semaphore semaphore;  public datachannel(int[] array) {     this.semaphore = new semaphore(array.length);      this.array = array;    this.p = 0;    this.c = 0;  }  public  void writedata (int data) {     try {        system.out.println("--- try write array["+p+"]="+data);        this.semaphore.acquire();        this.array[p] = data;         this.p = (p + 1) % array.length;     } catch (interruptedexception e) {         e.printstacktrace();     }   }  public int readdata() {    this.semaphore.release();    int data = array[c];    system.out.println("!!! try read data array["+c+"]="+data);    this.c = (c + 1) % array.length;    return data; }} 

start point:

public class app {  public static void main(string[] args) throws interruptedexception {         int[] array = new int[5];         datachannel buffer = new datachannel(array);          producer producer = new producer (buffer);        consumer consumer = new consumer (buffer);         producer.start();        consumer.start();         try {            producer.join();            consumer.join();             system.out.println("produced: "+producer.sum +" consumed:"+consumer.sum);             // here problem, bad implementation            if(producer.sum!=consumer.sum)throw new exception("not correct imlementation");         } catch (exception e) {            e.printstacktrace();     }   } 

}


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -