zoukankan      html  css  js  c++  java
  • Python3.x 多线程编程

    1

    import  threading
    import  time
    from threading import current_thread
    
    def myThread(arg1, arg2):
        print(current_thread().getName(),'start')
        print('%s %s'%(arg1, arg2))
        time.sleep(1)
        print(current_thread().getName(),'stop')
    
    
    for i in range(1,4,1):
        # t1 = myThread(i, i+1)
        t1 = threading.Thread(target=myThread,args=(i, i+1))
        t1.start()
    
    print(current_thread().getName(),'end')
    
    # 运行结果
    Thread-1 start
    1 2
    Thread-2 start
    2 3
    Thread-3 start
    3 4
    MainThread end
    Thread-2 stop
    Thread-1 stop
    Thread-3 stop

    2

    import  threading
    from threading import  current_thread
    
    class Mythread(threading.Thread):
        def run(self):
            print(current_thread().getName(),'start')
            print('run')
            print(current_thread().getName(),'stop')
    
    
    t1 = Mythread()
    t1.start()
    t1.join()
    
    print(current_thread().getName(),'end')
    
    # 运行结果
    Thread-1 start
    run
    Thread-1 stop
    MainThread end

    3. 生产者和消费者

    from threading import Thread,current_thread
    import time
    import random
    from queue import Queue
    
    queue = Queue(5)
    
    class ProducerThread(Thread):
        def run(self):
            name = current_thread().getName()
            nums = range(100)
            global queue
            while True:
                num = random.choice(nums)
                queue.put(num)
                print('生产者 %s 生产了数据 %s' %(name, num))
                t = random.randint(1,3)
                time.sleep(t)
                print('生产者 %s 睡眠了 %s 秒' %(name, t))
    
    class ConsumerTheard(Thread):
        def run(self):
            name = current_thread().getName()
            global queue
            while True:
                num = queue.get()
                queue.task_done()
                print('消费者 %s 消耗了数据 %s' %(name, num))
                t = random.randint(1,5)
                time.sleep(t)
                print('消费者 %s 睡眠了 %s 秒' % (name, t))
    
    
    p1 = ProducerThread(name = 'p1')
    p1.start()
    p2 = ProducerThread(name = 'p2')
    p2.start()
    p3 = ProducerThread(name = 'p3')
    p3.start()
    c1 = ConsumerTheard(name = 'c1')
    c1.start()
    c2 = ConsumerTheard(name = 'c2')
    c2.start()
    
    # 运行结果
    生产者 p1 生产了数据 76
    生产者 p2 生产了数据 89
    生产者 p3 生产了数据 37
    消费者 c1 消耗了数据 76
    消费者 c2 消耗了数据 89
    
    Execution Timed Out
    
    undefined
  • 相关阅读:
    验证guid()类型值的函数
    jquery时期到计时插件
    最简单快速的Apache二级域名实现方法
    线程和线程的常用方法
    Mobile WEB前端研发流程
    HTML5标莶使用初级技巧
    前端开发中常见的HTML5标签乱用案例
    iPad应用的10大用户体验设计准则
    移动平台3G手机网站前端开发布局技巧汇总
    分享HTML 5的参考手册,演讲稿,电子书和教程
  • 原文地址:https://www.cnblogs.com/sunnycindy/p/15514948.html
Copyright © 2011-2022 走看看