多任务-线程

2020-07-13  本文已影响0人  我竟无言以对_1202
import time
import threading


def sing():
    for i in range(5):
        print("唱歌")
        time.sleep(1)


def dance():
    for i in range(5):
        print("跳舞")
        time.sleep(1)


def main():
    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)
    t1.start()
    t2.start()

    # 查看线程数
    # length = len(threading.enumerate())
    # print(length)
    while True:
        print(threading.enumerate())
        time.sleep(1)

if __name__ == "__main__":
    main()

必要时可封装

#coding=utf-8

import threading
import time

class MyThread(threading.Thread):
    def run(self):
        for i in range(3):
            time.sleep(1)
            msg = "I'm " + self.name + '@' + str(i)
            print(msg)


if __name__ == "__main__":
    t = MyThread()
    t.start()

多线程之间全局变量共享,并传参数

import threading
import time

g_nums = [11,22]
def test1(temp):
    print("test1 g_num %s"% temp)

def test2(temp):
    print("test2 g_num %s" % temp)

def main():
    t1 = threading.Thread(target=test1, args=(g_nums,))
    t2 = threading.Thread(target=test2, args=(g_nums,))

    t1.start()
    time.sleep(1)
    t2.start()

if __name__ == "__main__":
    main()
上一篇 下一篇

猜你喜欢

热点阅读