0

I'm trying to understand semaphores. If I want to print out something like @//}}} repeatedly (with \n after each character), how could I do that with semaphores printing only 1 visible character at a time? I have an idea on how to print out one character each using similar code for each semaphore:

public static class PrintB implements Runnable // similar class for each semaphore
    {
        public void run(){
            for (int i=0; i<count; i++) { // printing lots to see functionality
                try {
                    printableB.acquire(); // the semaphore
                }
                catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                System.out.printf( "%s\n", "/"); // Need 2 /'s
                printableC.release(); // handled B's print, move to C
            }
        }
    }    

The problem here is that the rest of my code will only print "@/}" and not "@//}}}". I don't want to just put in other print statements to accomplish this. I want to only use semaphore-related statements like .acquire() and .release() (I'm trying to learn about them after all!). Any ideas? Thank you!

ChiCity
  • 1
  • 1
  • I think you'll need to share more details about your code for us to offer a proper answer. However, acquiring a semaphore and releasing another sounds like trouble. – afsantos Oct 26 '14 at 18:37
  • Yes, I don't know why the rest of your code doesn't print because you don't show the rest of your code. Only other thought: `release()` must really go in a `finally` block or you run the risk of never releasing that semaphore. – markspace Oct 26 '14 at 18:43

0 Answers0