1115. 交替打印FooBar

同思路解法:

https://leetcode-cn.com/problems/print-foobar-alternately/solution/liang-ge-xin-hao-liang-jiao-ti-kong-zhi-by-atizose/

新增知識點:

1、Semaphore? ?https://www.cnblogs.com/klbc/p/9500947.html??Semaphore 是 synchronized 的加強版,作用是控制線程的并發數量。就這一點而言,單純的synchronized 關鍵字是實現不了的。

2、啟用線程的寫法:

public static void main(String[] args) throws InterruptedException {

? ? ? ? FooBar fooBar = new FooBar(3);

? ? ? ? Thread t1 = new Thread(()->{

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? fooBar.foo(()->{

? ? ? ? ? ? ? ? ? ? System.out.print("foo");

? ? ? ? ? ? ? ? });

? ? ? ? ? ? } catch (InterruptedException e) {

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? }

? ? ? ? });

? ? ? ? Thread t2 = new Thread(()->{

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? fooBar.bar(()->{

? ? ? ? ? ? ? ? ? ? System.out.print("bar");

? ? ? ? ? ? ? ? });

? ? ? ? ? ? } catch (InterruptedException e) {

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? }

? ? ? ? });

? ? ? ? t2.start();

? ? ? ? t1.start();

? ? }

作者:atizose

鏈接:https://leetcode-cn.com/problems/print-foobar-alternately/solution/liang-ge-xin-hao-liang-jiao-ti-kong-zhi-by-atizose/

來源:力扣(LeetCode)

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。