zoukankan      html  css  js  c++  java
  • 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()
  • 相关阅读:
    Cookie同Session的关系 (2)
    Java Web应用开发概述
    Oracle客户端工具连接数据库服务器问题汇总
    java中使用JSCH包,SFTP及SSH2文件操作及远程命令执行
    javascript学习实录 之九(选择样式,改变文字效果) 刘小小尘
    用python给MP3加封面图片,修改作者,专辑等信息
    超像素分割技术发展情况梳理(Superpixel Segmentation)计算机视觉专题3
    android 应用程序的内存分析
    查询成绩
    sharepoint 2010 获取列表术语数据源方法
  • 原文地址:https://www.cnblogs.com/yijierui/p/13873997.html
Copyright © 2011-2022 走看看