Semaphore:
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SemaphoreExample {
public static void main(String args[]) {
Semaphore semaphore = new Semaphore(3);
Sharedresource sr = new Sharedresource(semaphore);
Thread t1 = new Thread(sr, "1");
Thread t2 = new Thread(sr, "2");
Thread t3 = new Thread(sr, "3");
Thread t4 = new Thread(sr, "4");
Thread t5 = new Thread(sr, "5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Sharedresource implements Runnable {
CommonResources cr = new CommonResources();
Semaphore semaphore;
Sharedresource(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cr.getCount();
semaphore.release();
}
}
class CommonResources {
private final Lock lock = new ReentrantLock();
public void getCount() {
// synchronized (Object.class) {
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
lock.unlock();
}
// }
}
}
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SemaphoreExample {
public static void main(String args[]) {
Semaphore semaphore = new Semaphore(3);
Sharedresource sr = new Sharedresource(semaphore);
Thread t1 = new Thread(sr, "1");
Thread t2 = new Thread(sr, "2");
Thread t3 = new Thread(sr, "3");
Thread t4 = new Thread(sr, "4");
Thread t5 = new Thread(sr, "5");
t1.start();
t2.start();
t3.start();
t4.start();
t5.start();
}
}
class Sharedresource implements Runnable {
CommonResources cr = new CommonResources();
Semaphore semaphore;
Sharedresource(Semaphore semaphore) {
this.semaphore = semaphore;
}
public void run() {
try {
semaphore.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
cr.getCount();
semaphore.release();
}
}
class CommonResources {
private final Lock lock = new ReentrantLock();
public void getCount() {
// synchronized (Object.class) {
lock.lock();
try {
for (int i = 0; i < 5; i++) {
System.out.println("Thread--"
+ Thread.currentThread().getName() + " i is " + i);
}
} finally {
lock.unlock();
}
// }
}
}
No comments:
Post a Comment