乐趣区

关于python:使用二个线程交替打印1100python实现

import threading
import time

num = 0


class MyThread(threading.Thread):
    def __init__(self, m_sig, o_sig, thread_id):
        threading.Thread.__init__(self, daemon=True)
        self.m_singal = m_sig
        self.o_singal = o_sig
        self.id = thread_id

    def run(self):
        while True:
            self.m_singal.wait()
            global num
            num = num + 1
            if num >= 100:
                break
            print("thread id {}: {}".format(self.id, num))
            self.o_singal.set()
            self.m_singal.clear()


if __name__ == "__main__":
    singal1 = threading.Event()
    singal2 = threading.Event()

    thread1 = MyThread(singal1, singal2, 1)
    thread2 = MyThread(singal2, singal1, 2)

    thread1.start()
    thread2.start()

    singal1.set()

    time.sleep(2)

    singal1.set()
    singal2.set()
退出移动版