Class FooBar
java.lang.Object
g1101_1200.s1115_print_foobar_alternately.FooBar
1115 - Print FooBar Alternately.<p>Medium</p>
<p>Suppose you are given the following code:</p>
<p>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”); } } }</p>
<p>The same instance of <code>FooBar</code> will be passed to two different threads:</p>
<ul>
<li>thread <code>A</code> will call <code>foo()</code>, while</li>
<li>thread <code>B</code> will call <code>bar()</code>.</li>
</ul>
<p>Modify the given program to output <code>"foobar"</code> <code>n</code> times.</p>
<p><strong>Example 1:</strong></p>
<p><strong>Input:</strong> n = 1</p>
<p><strong>Output:</strong> “foobar”</p>
<p><strong>Explanation:</strong> There are two threads being fired asynchronously. One of them calls foo(), while the other calls bar(). “foobar” is being output 1 time.</p>
<p><strong>Example 2:</strong></p>
<p><strong>Input:</strong> n = 2</p>
<p><strong>Output:</strong> “foobarfoobar”</p>
<p><strong>Explanation:</strong> “foobar” is being output 2 times.</p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= n <= 1000</code></li>
</ul>
-
Constructor Summary
Constructors -
Method Summary
-
Constructor Details
-
FooBar
public FooBar(int n)
-
-
Method Details
-
foo
- Throws:
InterruptedException
-
bar
- Throws:
InterruptedException
-