• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Concurrency Utilities

 
Ranch Hand
Posts: 115
Eclipse IDE Tomcat Server Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
in concurrency utilities we use "Semaphore" how the semaphore work??
we assign the values of permit in "Semaphore(value) constructor, how the permit work???

How the semaphore work in this code???

// An implementation of a producer and consumer
// that use semaphores to control synchronization.

import java.util.concurrent.Semaphore;

class Q {
int n;

// Start with consumer semaphore unavailable.
static Semaphore semCon = new Semaphore(0);
static Semaphore semProd = new Semaphore(1);

void get() {
try {
semCon.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}

System.out.println("Got: " + n);
semProd.release();
}

void put(int n) {
try {
semProd.acquire();
} catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}

this.n = n;
System.out.println("Put: " + n);
semCon.release();
}
}

class Producer implements Runnable {
Q q;

Producer(Q q) {
this.q = q;
new Thread(this, "Producer").start();
}

public void run() {
for(int i=0; i < 20; i++) q.put(i);
}
}

class Consumer implements Runnable {
Q q;

Consumer(Q q) {
this.q = q;
new Thread(this, "Consumer").start();
}

public void run() {
for(int i=0; i < 20; i++) q.get();
}
}

class ProdCon {
public static void main(String args[]) {
Q q = new Q();
new Consumer(q);
new Producer(q);
}
}
 
Greenhorn
Posts: 13
Oracle C++ Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
read this link
http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/Semaphore.html#Semaphore%28int%29

at least read the functions Semaphore(), release() and acquire()
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic