• python线程threading处理任务并发一


    python用多线程处理任务并发情况。thread生命周期:1、创建对象时,代表 Thread 内部被初始化。2、调用 start() 方法后,thread 会开始运行。

    3、thread 代码正常运行结束或者是遇到异常,线程会终止。函数表达式:threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

    直接创建thread,传递callable(可调用)对象。从输出可以看出,两个任务同时执行。

    import threading
    import time
    
    def test():
    
        for i in range(5):
            print('test ',i,time.ctime())
            time.sleep(1)
    
    
    thread = threading.Thread(target=test)
    thread.start()
    
    for i in range(5): print("main",i,time.ctime()) time.sleep(1)
    """output"""
    
    test main  00 Sun Oct 25 15:07:05 2020 
    Sun Oct 25 15:07:05 2020
    test main  11  Sun Oct 25 15:07:06 2020Sun Oct 25 15:07:06 2020
    
    test main  22 Sun Oct 25 15:07:07 2020 
    Sun Oct 25 15:07:07 2020
    test main  33  Sun Oct 25 15:07:08 2020Sun Oct 25 15:07:08 2020
    
    test main  44  Sun Oct 25 15:07:09 2020
    Sun Oct 25 15:07:09 2020

     thread.current_thread() .name返回线程名字

    import threading
    import time
    
    def test():
    
        for i in range(5):
            print(threading.current_thread().name+"test",i,time.ctime())
            time.sleep(1)
    
    
    thread = threading.Thread(target=test,name="testthread")
    thread.start()
    
    for i in range(5):
        print(threading.current_thread().name+"main",i,time.ctime())
        time.sleep(1)
    """output"""
    
    testthreadtestMainThreadmain  00  Sun Oct 25 15:35:55 2020Sun Oct 25 15:35:55 2020
    
    MainThreadmaintestthreadtest  11  Sun Oct 25 15:35:56 2020Sun Oct 25 15:35:56 2020
    
    MainThreadmaintestthreadtest 2 2 Sun Oct 25 15:35:57 2020 
    Sun Oct 25 15:35:57 2020
    MainThreadmain testthreadtest 33  Sun Oct 25 15:35:58 2020Sun Oct 25 15:35:58 2020
    
    testthreadtestMainThreadmain  44  Sun Oct 25 15:35:59 2020Sun Oct 25 15:35:59 2020

     Thread 的 is_alive() 方法查询线程是否还在运行。is_alive() 返回 True 的情况是 Thread 对象被正常初始化,start() 方法被调用,

    然后线程的代码还在正常运行。join()提供线程阻赛手段,让一个线程先运行,一个后运行。默认的情况是,join() 会一直等待对应线程的结束,

    但可以通过参数赋值,等待规定的时间就好了:join(timeout=None)

    import threading
    import time
    
    def test():
    
        for i in range(5):
            print(threading.current_thread().name+"test",i,time.ctime())
            time.sleep(0.5)
    
    
    thread = threading.Thread(target=test,name="testthread")
    thread.start()
    thread.join()
    
    
    for i in range(5):
        print(threading.current_thread().name+"main",i,time.ctime())
        print(thread.name + "is alive", thread.is_alive())
        time.sleep(1)
    """output"""
    
    testthreadtest 0 Sun Oct 25 16:15:08 2020
    testthreadtest 1 Sun Oct 25 16:15:09 2020
    testthreadtest 2 Sun Oct 25 16:15:09 2020
    testthreadtest 3 Sun Oct 25 16:15:10 2020
    testthreadtest 4 Sun Oct 25 16:15:10 2020
    MainThreadmain 0 Sun Oct 25 16:15:11 2020
    testthreadis alive False
    MainThreadmain 1 Sun Oct 25 16:15:12 2020
    testthreadis alive False
    MainThreadmain 2 Sun Oct 25 16:15:13 2020
    testthreadis alive False
    MainThreadmain 3 Sun Oct 25 16:15:14 2020
    testthreadis alive False
    MainThreadmain 4 Sun Oct 25 16:15:15 2020
    testthreadis alive False

    thread中的 daemon 属性。Thread 的构造方法中有一个 daemon 参数,默认是 None。如果要达到,MainThread 结束,子线程也立马结束,怎么做呢?

    可以在子线程的构造器中传递 daemon 的值为 True。 thread = threading.Thread(target=test,name='TestThread',daemon=True)

    面向对象编程实现以上线程代码:自定义一个 Thread 的子类,然后复写它的 run() 方法

    import threading
    import time
    
    class TestThread(threading.Thread):
    
        def __init__(self, name=None):
    
            threading.Thread.__init__(self,name=name)
    
        def run(self):
            for i in range(5):
                print(threading.current_thread().name + "test",i)
                time.sleep(1)
    
    
    thread = TestThread(name="testthread")
    thread.start()
    
    for i in range(5):
        print(threading.current_thread().name + "main",i)
        print(thread.name + "is alive", thread.is_alive())
        time.sleep(1)

    睡眠排序法

    import threading
    from time import sleep,ctime
    
    lst=[1,3,2,4]
    
    def f(n):
        sleep(n)
        print(n,threading.current_thread().name,ctime())
    
    threads=[]
    for i in range(len(lst)):
        thread = threading.Thread(target=f,args=(lst[i]))
        threads.append(thread)
    
    for i in range(len(lst)):
        threads[i].start()
    """OUTPUT"""
    
    1 Thread-1 Sun Oct 25 22:40:57 2020
    2 Thread-3 Sun Oct 25 22:40:58 2020
    3 Thread-2 Sun Oct 25 22:40:59 2020
    4 Thread-4 Sun Oct 25 22:41:00 2020
    import threading
    
    class MyThreading(threading.Thread):
        def __init__(self, func, arg):
            super(MyThreading, self).__init__()
            self.func = func
            self.arg = arg
        # 重写run()方法
        def run(self):
            self.func(self.arg)
    
    
    def my_func(args):
        '''
        此处可以把你想让线程做的事定义在这里
        '''
        print("我是业务函数...")
        pass
    obj = MyThreading(my_func, 123)
    obj.start()
    import threading
    from time import sleep,ctime
    
    class Mythread(threading.Thread):
        def __init__(self, func, args):
            threading.Thread.__init__(self)
            self.func = func
            self.args = args
    
        #重写run()方法
        def run(self):
            self.func(self.args)
            
    
    lst = [2,4,3,5]
    
    def my_func(n):
        sleep(n)
        print(n,threading.current_thread().name,ctime())
    
    
    threads=[]
    for i in range(len(lst)):
        thread = Mythread(my_func,args=(lst[i]))
        threads.append(thread)
    
    for i in range(len(lst)):
        threads[i].start()
  • 相关阅读:
    SQL Server CHARINDEX和PATINDEX详解
    MVC ListBoxFor raises “value cannot be null” exception
    jquery.uploadify动态传递表单元素
    C# 判断一字符串是否为合法数字(正则表达式)
    jquery 操作Listbox
    JQuery 操作 ListBox间移动和ListBox内移动
    jQuery获取Select选择的Text和 Value
    SQL 语句的执行效率
    JSON 序列化长度限制问题
    C#中利用FileSystemWatcher对单个文件内容的监视
  • 原文地址:https://www.cnblogs.com/yijierui/p/13873997.html
Copyright © 2020-2023  润新知