Python多线程threading创建及使用方法解析
一、线程创建方法
1. 普通创建
import threadingdef run(name): for i in range(3): print(name)if __name__ == ’__main__’: t1 = threading.Thread(target=run, args=('t1',)) t2 = threading.Thread(target=run, args=('t2',)) t1.start() t2.start()--------------------------------------------t1t2t2t1t2t1
2. 自定义线程类
import threadingclass MyThread(threading.Thread): def __init__(self, name): super(MyThread, self).__init__() self.name = name def run(self): for i in range(3): print(self.name)if __name__ == '__main__': t1 = MyThread('t1') t2 = MyThread('t2') t1.start() t2.start()
二、线程的使用
1.守护线程
子线程会随着主线程的结束而结束
t = threading.Thread(target=run, args=('t1',))t.setDaemon(True) # 把子进程设置为守护线程,必须在start()之前设置t.start()
2.主线程等待子线程结束
t = threading.Thread(target=run, args=('t1',))t.setDaemon(True)t.join() # 设置主线程等待子线程结束t.start()
3.互斥锁
from threading import Thread,Lockn = 10def run(): global n locker.acquire() n -= 1 locker.release()if __name__ == ’__main__’: locker = Lock() t1 = Thread(target=run) t2 = Thread(target=run) t1.start() t2.start()
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持好吧啦网。
相关文章: