Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package semaphores;
- import java.util.concurrent.Semaphore;
- public final class ABCwithSem {
- private static final int COUNT = 30;
- private static int COUNTER = 0;
- private static final int STEP = 10;
- private static final Semaphore a = new Semaphore(0 ,true);
- private static final Semaphore b = new Semaphore(0, true);
- private static final Semaphore c = new Semaphore(0, true);
- private static final Semaphore d = new Semaphore(0, true);
- private static final Semaphore e = new Semaphore(0, true);
- private static final Semaphore f = new Semaphore(1, true);
- public static void main(String[] args) {
- new A().start();
- new B().start();
- new C().start();
- new D().start();
- new E().start();
- new F().start();
- }
- private static final class A extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT; i++) {
- a.acquire();
- myPrint("A ");
- f.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static final class B extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT*2; i++) {
- b.acquire();
- myPrint("B ");
- f.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static final class C extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT; i++) {
- c.acquire();
- myPrint("C ");
- f.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static final class D extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT; i++) {
- d.acquire();
- myPrint("D ");
- f.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static final class E extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT; i++) {
- d.acquire();
- myPrint("E ");
- f.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static final class F extends Thread {
- @Override
- public void run() {
- try {
- for (int i = 0; i < COUNT; i++) {
- f.acquire();
- d.release();
- f.acquire();
- c.release();
- f.acquire();
- b.release(2);
- f.acquire(2);
- a.release();
- f.acquire();
- c.release();
- f.acquire();
- e.release();
- f.acquire();
- a.release();
- f.acquire();
- b.release();
- f.acquire();
- e.release();
- }
- } catch (InterruptedException ex) {
- }
- }
- }
- private static synchronized void myPrint(String s) {
- COUNTER++;
- System.out.print(s);
- if (COUNTER == STEP) {
- COUNTER = 0;
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement