#真线程 #定义四个线程锁,输出"A"后,释放B的锁,从而达到通知B import threading import sys #线程函数1控制次数,输出"A"后,释放B的锁... def ThreadFun1(num): global stop for i in range(num): lock1.acquire() res.append("A") if i == num - 1:#输出完最后一次,就通知其他线程输完一次就可以结束了 stop = True lock2.release()#释放B的锁,从而达到通知B def ThreadFun2(): global stop while True: lock2.acquire() res.append("B") lock3.release() if stop == True:#结束线程 return def ThreadFun3(): global stop while True: lock3.acquire() res.append("C") lock4.release() if stop == True: return def ThreadFun4(): global stop while True: lock4.acquire() res.append("D") lock1.release()#输出完"D"释放"A"的锁 if stop == True: return while True: try: N = int(input()) res = [] stop = False #定义四个线程锁 lock1 = threading.Lock() lock2 = threading.Lock() lock3 = threading.Lock() lock4 = threading.Lock() #给其他三个线程加上锁先 lock2.acquire() lock3.acquire() lock4.acquire() #定义4个线程,只有第一个有参数,用于初始化输出A次数 t1 = threading.Thread(target=ThreadFun1, args=(N,)) t2 = threading.Thread(target=ThreadFun2, args=()) t3 = threading.Thread(target=ThreadFun3, args=()) t4 = threading.Thread(target=ThreadFun4, args=()) #开启线程 t1.start() t2.start() t3.start() t4.start() #等待线程结束 t1.join() t2.join() t3.join() t4.join() #线程都结束后,输出结果 print("".join(res)) except: # print(sys.exc_info()) break # import sys # import threading # while True: # try: # N = int(input()) # threadLock = threading.Lock() # index = 1 # res = [] # class AddAlpha(threading.Thread): # def __init__(self, N, threadId): # threading.Thread.__init__(self) # # super(AddAlpha,self).__init__() # # super.__init__(self) # self.n = N # self.threadId = threadId # self.count = 0 # def run(self): # global index # while self.count < self.n: # threadLock.acquire() # if index == 1 and self.threadId == 1: # res.append("A") # self.count += 1 # index = 2 # if index == 2 and self.threadId == 2: # res.append("B") # self.count += 1 # index = 3 # if index == 3 and self.threadId == 3: # res.append("C") # self.count += 1 # index = 4 # if index == 4 and self.threadId == 4: # res.append("D") # self.count += 1 # index = 1 # threadLock.release() # threads = [] # threads.append(AddAlpha(N,1)) # threads.append(AddAlpha(N,2)) # threads.append(AddAlpha(N,3)) # threads.append(AddAlpha(N,4)) # for thread in threads: # thread.start() # for thread in threads: # thread.join() # print("".join(res)) # except: # # print(sys.exc_info()) # break