Java semaphore to syncronize printing to screen

Posted by Travis Griswald on Stack Overflow See other posts from Stack Overflow or by Travis Griswald
Published on 2012-11-18T16:37:14Z Indexed on 2012/11/18 17:01 UTC
Read the original article Hit count: 277

Filed under:
|

I'm currently stuck on a bit of homework and was wondering if anyone could help -

I have to use semaphores in java to syncronize printing letters from 2 threads - one printing "A" and one printing "B". I cannot print out more than 2 of the same character in a row, so output should look like

AABABABABABBABABABABAABBAABBABABA

At the moment I have 3 semaphores, a binary mutex set to 1, and a counting semaphore, and my thread classes look something like this -

public void run() {
    while (true) {
        Time.delay(RandomGenerator.integer(0,20));
        Semaphores.mutex.down ();
        System.out.println (produce());

          if (printCount > 1)
          { printCount = 0;
                Semaphores.mutex.up ();
                Semaphores.printB.up();
          }
    } 
}
public String produce() {
    printCount++;
    return "A";
}


public void run() {
    while (true) {
        Time.delay(RandomGenerator.integer(0,20));
        Semaphores.mutex.down ();
        System.out.println (produce());

          if (printCount > 1)
          { printCount = 0;
                Semaphores.mutex.up ();
                Semaphores.printA.up();
          }
    } 
}
public String produce() {
    printCount++;
    return "B";
}

Yet whatever I try it either deadlocks, or it seems to be working only printing 2 in a row at most, but always seems to print 3 in a row every now and again!

Any help is much appreciated, not looking code or anything just a few pointers if possible :)

© Stack Overflow or respective owner

Related posts about java

Related posts about multithreading