zoukankan      html  css  js  c++  java
  • python多线程threading的使用

    一、线程创建方法

    1. 普通创建

    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. 自定义线程类

    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.互斥锁

    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()
  • 相关阅读:
    SSM环境搭建
    spring 开发 Tars
    Tars --- Hello World
    Java IO流
    Java集合
    常用类
    Pwn With longjmp
    格式化字符串漏洞利用实战之 njctf-decoder
    一步一步 Pwn RouterOS之ctf题练手
    srop实战
  • 原文地址:https://www.cnblogs.com/LMIx/p/12678351.html
Copyright © 2011-2022 走看看