[Programming Problem] Print FooBar Alternately

Suppose you are given the following code:

class FooBar {
  public void foo() {
    for (int i = 0; i < n; i++) {
  public void bar() {
    for (int i = 0; i < n; i++) {

The same instance of FooBar will be passed to two different threads:

  • thread A will call foo(), while
  • thread B will call bar().

Modify the given program to output “foobar” n times.

Example 1:
Input: n = 1
Output: “foobar”
Explanation: There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar().
“foobar” is being output 1 time.

Example 2:
Input: n = 2
Output: “foobarfoobar”
Explanation: “foobar” is being output 2 times.

[Problem Link]

Why use Semaphore and not ReentrantLock?

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available. When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the “lock” can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

class FooBar {
    private int n;
    private final Semaphore mutexFoo = new Semaphore(1);
    private final Semaphore mutexBar = new Semaphore(1);
    public FooBar(int n) {
        this.n = n;
        try {
        } catch ( Exception e ) {}
    public void foo(Runnable printFoo) throws InterruptedException {
        for (int i = 0; i < n; i++) {
            // printFoo.run() outputs "foo". Do not change or remove this line.
    public void bar(Runnable printBar) throws InterruptedException {
        for (int i = 0; i < n; i++) {     
            // printBar.run() outputs "bar". Do not change or remove this line.

17 thoughts on “[Programming Problem] Print FooBar Alternately

  1. Thank you a lot for giving everyone a very spectacular possiblity to read critical reviews from here. It is usually so cool plus full of a good time for me personally and my office peers to search your site at the very least 3 times in one week to see the newest issues you have. And lastly, I’m so at all times fulfilled considering the astounding knowledge you give. Selected two tips on this page are absolutely the most beneficial we’ve ever had.

  2. I wish to get across my gratitude for your generosity supporting men and women who must have help on this important area of interest. Your personal commitment to getting the message all through has been pretty functional and have permitted some individuals like me to attain their pursuits. Your personal warm and helpful tutorial means much a person like me and even further to my colleagues. Many thanks; from each one of us.

  3. Thanks so much for providing individuals with an extremely terrific chance to check tips from here. It can be so cool and as well , jam-packed with a lot of fun for me personally and my office mates to search the blog minimum 3 times in a week to study the newest stuff you will have. And lastly, I am actually pleased with the exceptional things you give. Some 4 areas in this posting are indeed the simplest I have ever had.

  4. Needed to compose you a very little remark to give thanks as before on the precious guidelines you’ve featured at this time. It’s extremely generous of people like you to offer unreservedly all numerous people would’ve sold for an ebook to end up making some profit for themselves, and in particular since you could have done it if you desired. These advice likewise acted to become good way to know that other people online have similar passion just like mine to figure out very much more around this matter. I am certain there are millions of more fun periods in the future for many who start reading your website.

  5. I’m just writing to make you be aware of what a nice experience our princess obtained going through your site. She figured out numerous issues, which included what it’s like to have a wonderful helping style to get many more really easily learn specified extremely tough topics. You actually did more than people’s desires. Thanks for supplying the good, trusted, explanatory as well as cool thoughts on this topic to Kate.

  6. I must show my appreciation for your generosity for men and women who should have assistance with your niche. Your real dedication to passing the solution all-around appeared to be quite functional and has frequently enabled guys and women like me to reach their targets. Your entire warm and helpful recommendations denotes this much a person like me and somewhat more to my fellow workers. Regards; from everyone of us.

  7. I wish to convey my passion for your kindness giving support to visitors who have the need for help on in this subject. Your real dedication to passing the solution all through appears to be unbelievably beneficial and have in most cases permitted professionals much like me to realize their dreams. Your own invaluable facts implies a lot a person like me and extremely more to my office colleagues. Warm regards; from each one of us.

  8. I intended to draft you this tiny note in order to thank you once again with your pleasing pointers you’ve featured at this time. It has been surprisingly generous with people like you to make unhampered just what a lot of folks might have offered as an electronic book to earn some bucks for their own end, chiefly given that you could have done it in the event you desired. The techniques additionally acted to be a easy way to be aware that other people online have the identical desire like my own to realize a lot more concerning this issue. I am sure there are thousands of more fun opportunities up front for those who see your website.

Leave a Reply

Your email address will not be published. Required fields are marked *