异步线程启动
Semaphore是一种在多线程环境下使用的设施,该设施负责协调各个线程,以保证它们能够正确、合理的使用公共资源的设施,也是操作系统中用于控制进程同步互斥的量。Semaphore是一种计数信号量,用于管理一组资源,内部是基于AQS的共享模式。它相当于给线程规定一个量从而控制允许活动的线程数。
Semaphore(int s):构造方法,创建具有给定许可数的计数信号量并设置为非公平信号量。
Semaphore(int s,boolean fair):构造方法,当fair为true时,创建具有给定许可数的计数信号量并设置为公平信号量。
void acquire():获取一个许可前线程将一直阻塞,相当于占了一个车位。
void acquire(int n):获取许可前线程将一直阻塞,相当于占了n个车位。
void release():释放一个许可,将其返回给信号量。
代码
from threading import *
class Foo:
def init(self):
self.s1=Semaphore(1)
self.s2=Semaphore(0)
self.s3=Semaphore(0)
def first(self, printFirst: 'Callable[[], None]') -> None:
# printFirst() outputs "first". Do not change or remove this line.
self.s1.acquire()
printFirst()
self.s2.release()
def second(self, printSecond: 'Callable[[], None]') -> None:
# printSecond() outputs "second". Do not change or remove this line.
self.s2.acquire()
printSecond()
self.s3.release()
def third(self, printThird: 'Callable[[], None]') -> None:
# printThird() outputs "third". Do not change or remove this line.
self.s3.acquire()
printThird()