多线程模块threading

Circle / 2024-11-07 / 原文

1.简单例子

import threading
import time

def run(n):
print("task", n)
time.sleep(2)

t1 = threading.Thread(target=run, args=("t1",))
t2 = threading.Thread(target=run, args=("t2",))

t1.start()
t2.start()


2.真使用时需要用类
import threading
class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print("run task", self.n)


t1 = MyThread("t1")
t2 = MyThread("t2")

t1.start()
t2.start()

3.设置守护线程(随主进程结束而结束)
import threading

class MyThread(threading.Thread):
def __init__(self, n):
super(MyThread, self).__init__()
self.n = n
def run(self):
print("run task", self.n)


t1 = MyThread("t1")
t2 = MyThread("t2")
t1.setDaemon(True) #把当前进程设置成守护进程
t2.setDaemon(True)
t1.start()
t2.start()