python-threading

使用 threading 创建线程

用threading.Thread创建类,实例化,然后用start()调用,用join()等待线程结束

import threading
import time #引入
exitFlag = 0 #1时中断线程
class myThread (threading.Thread): 
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID #定义线程id
        self.name = name #线程名字
        self.delay = delay #定义延迟时间
    def run(self): #用start()启用线程会调用run()
        print ("开始线程:" + self.name)
        print_time(self.name, self.delay, 5) #调用print_time方法
        print ("退出线程:" + self.name)
        
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit() #貌似是退出线程
        time.sleep(delay) #delay=1表示延时1print ("%s: %s" % (threadName, time.ctime(time.time()))) #time.ctime(time.time())将当前时间转换为字符串并返回
        counter -= 1
# 创建新线程
thread1 = myThread(1, "Thread-1", 1) #线程id,线程名,延时时间
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start() #启动run方法
thread2.start()
thread1.join() #等待至该线程终止
thread2.join()
print ("退出主线程")

线程同步

#!/usr/bin/python3
import threading
import time
class myThread (threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay
    def run(self):
        print ("开启线程: " + self.name)
        # 获取锁,用于线程同步
        threadLock.acquire() #此时只执行此线程
        print_time(self.name, self.delay, 3)
        # 释放锁,开启下一个线程
        threadLock.release() #此时执行下一个线程

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print ("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1

threadLock = threading.Lock()
threads = []
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# 开启新线程
thread1.start()
thread2.start()
# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
# 等待所有线程完成
for t in threads:
    t.join()
#以上四句等同于##############
thread1.join() 
thread2.join()
############################
print ("退出主线程")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值