• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Lucky
博客园    首页    新随笔    联系   管理    订阅  订阅

python_多线程

1.多线程的实现与阻塞

import time
import threading

def fun_yellow(num):
    for i in range(1,num+1):
        print('正在拿第:'+str(i)+"个黄苹果,当前时间:"+time.ctime()+'\n')
        time.sleep(1)

def fun_red(num):
    for i in range(1,num+1):
        print('正在拿第:'+str(i)+"个红苹果,当前时间:"+time.ctime()+'\n')
        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()+'\n')
        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()+'\n')
        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('所有任务都已执行完成!')

 

posted @ 2019-10-22 17:13  半仙儿~~~  阅读(239)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3