[Programming Problem] Print FooBar Alternately

Suppose you are given the following code:

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

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 {
            mutexBar.acquire();
        } 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.
            mutexFoo.acquire();
            printFoo.run();
            mutexBar.release();
        }
    }
 
    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.
            mutexBar.acquire();
            printBar.run();
            mutexFoo.release();
        }
    }
}

40 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.

  9. I wish to show my passion for your kind-heartedness in support of those who require assistance with your matter. Your real dedication to getting the solution along has been rather powerful and has usually permitted others like me to arrive at their desired goals. The warm and friendly key points entails much to me and still more to my office colleagues. Thanks a ton; from all of us.

  10. I would like to convey my respect for your kind-heartedness supporting men and women who really want help with that issue. Your personal commitment to passing the solution up and down appeared to be incredibly insightful and have always allowed folks much like me to achieve their dreams. This insightful guidelines signifies much to me and a whole lot more to my mates. With thanks; from everyone of us.

  11. I must voice my admiration for your generosity supporting visitors who really want guidance on this matter. Your real dedication to getting the solution along turned out to be certainly insightful and has all the time empowered somebody just like me to reach their endeavors. Your personal warm and helpful instruction entails so much a person like me and substantially more to my office colleagues. Thanks a lot; from each one of us.

  12. I not to mention my guys were found to be viewing the good information found on your site and so instantly got a terrible feeling I had not thanked you for those tips. All of the women appeared to be for this reason passionate to see them and have in effect quite simply been making the most of those things. Thank you for getting well helpful and also for picking varieties of extraordinary resources most people are really desirous to understand about. Our own sincere apologies for not saying thanks to earlier.

  13. I would like to point out my love for your kind-heartedness in support of those individuals that have the need for help with that question. Your very own commitment to getting the message along had been definitely invaluable and has truly permitted people like me to attain their dreams. Your entire insightful guideline indicates so much to me and substantially more to my office workers. Warm regards; from all of us.

  14. My wife and i have been very delighted when Peter could complete his research through your precious recommendations he got from your very own weblog. It is now and again perplexing to just be giving out guides others may have been selling. We discover we now have the writer to be grateful to because of that. The most important explanations you’ve made, the straightforward website navigation, the friendships your site help to create – it’s got mostly amazing, and it’s really making our son in addition to the family reckon that the subject is satisfying, and that is extraordinarily vital. Thank you for all the pieces!

  15. Thank you a lot for giving everyone such a pleasant possiblity to read in detail from here. It is usually very good plus packed with amusement for me and my office peers to search your site minimum three times in one week to see the newest tips you have got. Not to mention, I am always happy concerning the brilliant ideas you give. Some 4 points in this posting are certainly the best we have had.

  16. I needed to draft you the very little word to help give thanks the moment again just for the pleasing advice you’ve documented on this page. It is really incredibly open-handed with people like you to make publicly what a number of us might have marketed for an electronic book to end up making some cash for their own end, precisely considering the fact that you could possibly have done it in case you considered necessary. Those good ideas as well worked as a easy way to recognize that other people online have the same passion the same as my own to see more around this condition. I am sure there are many more pleasant periods ahead for people who read carefully your site.

  17. I wish to express my love for your kind-heartedness for folks that actually need help with this one situation. Your special commitment to getting the message around became remarkably practical and have usually made professionals just like me to get to their desired goals. Your warm and helpful advice denotes so much a person like me and a whole lot more to my office colleagues. Thanks a ton; from everyone of us.

  18. An interesting discussion is price comment. I think that you need to write extra on this topic, it may not be a taboo subject but typically people are not sufficient to talk on such topics. To the next. Cheers

  19. An interesting dialogue is price comment. I feel that you need to write extra on this subject, it won’t be a taboo subject however usually people are not sufficient to speak on such topics. To the next. Cheers

  20. Thanks for the ideas you have contributed here. Something else I would like to convey is that computer memory specifications generally increase along with other improvements in the technological know-how. For instance, when new generations of processors are made in the market, there is certainly usually a corresponding increase in the type calls for of both pc memory plus hard drive room. This is because the software operated by simply these processors will inevitably increase in power to take advantage of the new technology.

  21. Thank you so much for giving everyone such a remarkable chance to check tips from here. It is usually so beneficial and also jam-packed with amusement for me and my office peers to search your website at a minimum thrice per week to study the new issues you have got. Not to mention, I’m also at all times amazed concerning the tremendous principles you give. Certain 1 ideas on this page are easily the most effective we have ever had.

  22. I precisely desired to appreciate you yet again. I am not sure the things that I would have gone through in the absence of the concepts provided by you on that field. It absolutely was a real troublesome case for me personally, but noticing the very specialized fashion you dealt with that forced me to jump with gladness. I will be happier for your help and thus wish you realize what an amazing job your are carrying out instructing many others with the aid of your website. I am sure you haven’t come across all of us.

Leave a Reply to AlvinPal Cancel reply

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