multithreading - Semaphore not working as expected ,it is getting locked -


i using semaphore thread communication have 2 threads 1 oddthread , eventhread ,i printing value 1 10 oddthread print odd numbers between 1 10 , eventhread thread printing numbers between 1 10. have used semaphore threads communicate .what happening oddthread printing 1 , eventhread 2 , both stopped. not under standing happening.can body suggest.

   public class threadproducerconsumersemaphore {   /**  * @param args  */ public static void main(string[] args) {     semaphore p = new semaphore(1);      semaphore c = new semaphore(0);      oddthread producer = new oddthread(p, c);      eventhread consumer = new eventhread(p, c);     thread t1 = new thread(producer, "thread producer");     thread t2 = new thread(consumer, "thread consumer");     t1.start();     t2.start();   } }   class oddthread implements runnable { semaphore p; semaphore c;  public oddthread(semaphore p, semaphore c) {     super();     this.p = p;     this.c = c; }  int counter = 1;  @override public void run() {      while (true) {         try {             p.acquire(1);             system.out.println(thread.currentthread().getname() + " "                     + counter);             if (counter == 10) {                 break;             }             counter++;             c.release(1);          } catch (interruptedexception e) {             // todo auto-generated catch block             e.printstacktrace();         }      }  }  }    class eventhread implements runnable { semaphore p; semaphore c; int counter = 2;  public eventhread(semaphore p, semaphore c) {     super();     this.p = p;     this.c = c; }  @override public void run() {      while (true) {         try {             c.acquire(1);             system.out.println(thread.currentthread().getname() + " "                     + counter);             if (counter == 10) {                 break;             }             counter=counter+2;             p.acquire(1);         } catch (interruptedexception e) {             // todo auto-generated catch block             e.printstacktrace();         }      }  }   } 

your code can't correct, it's not symmetrical.

p.acquire(1); c.release(1);  c.acquire(1); p.acquire(1); 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -