• python_多线程


    1.多线程的实现与阻塞

    import time
    import threading
    
    def fun_yellow(num):
        for i in range(1,num+1):
            print('正在拿第:'+str(i)+"个黄苹果,当前时间:"+time.ctime()+'
    ')
            time.sleep(1)
    
    def fun_red(num):
        for i in range(1,num+1):
            print('正在拿第:'+str(i)+"个红苹果,当前时间:"+time.ctime()+'
    ')
            time.sleep(1)
    
    thread_yellow=threading.Thread(target=fun_yellow,args=(5,))
    thread_yellow.start()
    
    thread_red=threading.Thread(target=fun_red,args=(5,))
    thread_red.start()
    
    #阻塞主线程
    thread_yellow.join()
    thread_red.join()
    print('所有任务都已执行完成!')

    2.多线程同步:

    import time
    import threading
    
    all_num=0
    lock=threading.Lock()
    
    def fun_li(num):
        global all_num
        global lock
    
        #加锁
        lock.acquire()
        for i in range(1,num+1):
            all_num+=1
            print('李正在放第:'+str(i)+'个苹果,当前总共有:'+str(all_num)+'个苹果,当前时间:'+time.ctime()+'
    ')
            time.sleep(1)
        #解锁
        lock.release()
    
    def fun_zhang(num):
        global all_num
        global lock
    
        lock.acquire()
        for i in range(1,num+1):
            all_num+=1
            print('张正在放第:'+str(i)+'个苹果,当前总共有:'+str(all_num)+'个苹果,当前时间:'+time.ctime()+'
    ')
            time.sleep(1)
        lock.release()
    
    thread_yellow=threading.Thread(target=fun_li,args=(5,))
    thread_yellow.start()
    
    thread_red=threading.Thread(target=fun_zhang,args=(5,))
    thread_red.start()
    
    #阻塞主线程
    thread_yellow.join()
    thread_red.join()
    print('所有任务都已执行完成!')
  • 相关阅读:
    JVM参数设置-jdk8参数设置
    JVM参数配置详解-包含JDK1.8
    IntelliJ Idea 常用快捷键列表
    架构组织形式的讨论,以及架构师之路的建议
    ElasticSearch-6.3.2 linux 安装
    CAT 安装运行配置教程
    JPMML解析PMML模型并导入数据进行分析生成结果
    第9章 多态和抽象
    第10章 接口
    第8章 类的高级概念
  • 原文地址:https://www.cnblogs.com/myfy/p/11720975.html
Copyright © 2020-2023  润新知