同思路解法:
新增知識點:
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)
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。