java.lang.Object
g1101_1200.s1115_print_foobar_alternately.FooBar

public class FooBar extends java.lang.Object
1115 - Print FooBar Alternately.

Medium

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.

Constraints:

  • 1 <= n <= 1000
  • Constructor Summary

    Constructors
    Constructor
    Description
    FooBar(int n)
     
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    bar(java.lang.Runnable printBar)
     
    void
    foo(java.lang.Runnable printFoo)
     

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
  • Constructor Details

    • FooBar

      public FooBar(int n)
  • Method Details

    • foo

      public void foo(java.lang.Runnable printFoo) throws java.lang.InterruptedException
      Throws:
      java.lang.InterruptedException
    • bar

      public void bar(java.lang.Runnable printBar) throws java.lang.InterruptedException
      Throws:
      java.lang.InterruptedException