Python多线程threading创建及使用方法解析

2020-10-21 10:43:24 浏览数 (1)

一、线程创建方法

1. 普通创建

代码语言:javascript复制
import threading
def 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()

--------------------------------------------
t1
t2
t2
t1
t2
t1

2. 自定义线程类

代码语言:javascript复制
import threading
class 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.互斥锁

代码语言:javascript复制
from threading import Thread,Lock
n = 10
def 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()

以上就是本文的全部内容,希望对大家的学习有所帮助。

0 人点赞