Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to solve the problem of alternating printing FooBar with leetcode multithreading

Shulou Source: shulou.com Published: 2022-06-01 13:11:52 09月11日 Update

Editor to share with you how to solve the problem of alternating printing FooBar with leetcode multithreading, I believe most people do not know much about it, so share this article for your reference. I hope you will gain a lot after reading this article. Let's go to know it together.

We provide a class for the title: class FooBar {public void foo () {for (int I = 0; I < n; iTunes +) {print ("foo");}} public void bar () {for (int I = 0; I < n; iTunes +) {print ("bar");} two different threads will share a FooBar instance. One thread will call the foo () method, and the other thread will call the bar () method. Please design a modification program to ensure that "foobar" is output n times. Source: LeetCode link: https://leetcode-cn.com/problems/print-foobar-alternately copyright belongs to the collar buckle network. For commercial reprint, please contact official authorization. For non-commercial reprint, please indicate the source. Answer class FooBar {private int n; ReentrantLock lock = new ReentrantLock (); Condition fooCnd = lock.newCondition (); Condition barCnd = lock.newCondition (); boolean foo = true; public FooBar (int n) {this.n = n;} public void foo (Runnable printFoo) throws InterruptedException {lock.lock (); try {for (int I = 0; I < n) If (! foo) {fooCnd.await ();} foo = false; / / printFoo.run () outputs "foo". Do not change or remove this line. PrintFoo.run (); barCnd.signal ();}} finally {lock.unlock ();}} public void bar (Runnable printBar) throws InterruptedException {lock.lock (); try {for (int I = 0; I < n) ) {if (foo) {barCnd.await ();} foo = true; / / printBar.run () outputs "bar". Do not change or remove this line. PrintBar.run (); fooCnd.signal ();}} finally {lock.unlock ();}

Here, ReentrantLock's condition is used for conditional control.

These are all the contents of this article entitled "how to solve the problem of alternating printing FooBar with leetcode multithreading". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

Tags: Threads articles questions content methods different not so two provenance business most official instance more conditions sources knowledge programs networks works Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Information NVidia vpn MySQL Shulou Tech Info