先看看效果:
方法一(协程容易理解):
由于线程之间的执行是无序的,但是线程产生的协程(协程又叫微线程)是可以有序执行的,所以线程在此还是略显鸡肋的,这里要对生成器,迭代器有所了解,利用生成器中next方法将可迭代对象的值依次拿到拼接即可
望帮助到的朋友可以给个大拇指,谢谢啦?
import threading
import time
def work(a, index):
for i in range(26):
d = str(a[index])
index += 1
b = str(a[index])
c = d + b
index += 1
# print(c)
yield c
# mutex.release()
time.sleep(0.1)
def task():
for i in range(65, 91):
# for i in range(97,123):
# print(chr(i))
yield chr(i)
time.sleep(0.1)
if __name__ == '__main__':
a = []
index = 0
for i in range(1, 53):
a.append(i)
# 由于线程是无序的,所以在此线程是鸡肋,主要还是靠协程,它是微线程
thread_1 = threading.Thread(target=work,args=(a, index))
thread_2 = threading.Thread(target=task)
thread_1.start()
thread_2.start()
b1 = work(a, index)
b2 = task()
for _ in range(26):
a1 = next(b1)
a2 = next(b2)
print(a1 + a2)
方法二(利用互斥锁,递归函数解决,略微难点):
代码:
import threading
import time
lockA = threading.Lock()
lockB = threading.Lock()
def printNumber(n):
if n > 50:
return
n += 1
# A B 都上锁,解锁在对方函数内从而使无序的线程变得有序
lockA.acquire()
print("%d%d" % (n, n + 1), end="")
lockB.release()
# 让线程1先打印
time.sleep(0.01)
# 递归调用
printNumber(n + 1)
def printAlpha(n):
if n > 90:
return
lockB.acquire()
print(chr(n), end=' ')
lockA.release()
time.sleep(0.02)
# 递归调用
printAlpha(n + 1)
lockB.acquire()
t1 = threading.Thread(target=printNumber, args=(0,))
t2 = threading.Thread(target=printAlpha, args=(65,))
t1.start()
t2.start()