Python—使用两个线程循环输出100以内的奇数和偶数

import threading
import time

class A(threading.Thread):
    def __init__(self, n):
        super().__init__()
        self.num = n

    def run(self):
        global num
        locks.acquire()
        while True:
            if num%2 == 0:
                print("线程A:%d" %num)
                time.sleep(0.1)
                if num == self.num:
                    break
                num += 1
            else:
                locks.notify()
                if num == self.num:
                    break
                locks.wait()
        print("A线程释放")
        locks.release()

class B(threading.Thread):
    def __init__(self, n):
        super().__init__()
        self.num = n

    def run(self):
        global num
        locks.acquire()
        while True:
            if num%2 == 1:
                print("线程B:%d" %num)
                time.sleep(0.1)
                if num == self.num:
                    break
                num += 1
            else:
                locks.notify()
                if num == self.num:
                    break
                locks.wait()
        print("B线程释放")
        locks.release()

num = 0
locks = threading.Condition()
a = A(100)
b = B(100)
a.start()
b.start()

你可能感兴趣的:(Python—使用两个线程循环输出100以内的奇数和偶数)