python基础代码库-python基础:一个非常简单且详细的多线程代码

前言

多线程的好处应该不用多说吧?python语言内置了多线程功能支持,而不是单纯地作为底层操作系统的调度方式,从而简化了 Python 的多线程编程。

在实际应用,多线程还是很有用的,比如有时候可以同时下载多张图片,服务器响应多个请求啥的等等....还有很多实用东西

a7af5967a35a4bc9aa1468e37bdac38e

首先导入库

import threading

import time

类继承创建

class myThread (threading.Thread):

def __init__(self, threadID, name, counter):

threading.Thread.__init__(self)

self.threadID = threadID

self.name = name

self.counter = counter

def run(self):

print "Starting " + self.name

# 获得锁,成功获得锁定后返回True

# 可选的timeout参数不填时将一直阻塞直到获得锁定

# 否则超时后将返回False

threadLock.acquire()

print_time(self.name, self.counter, 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 = []

1ba1df7208304172826abff36e75bea4

创建新线程

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()

print("退出主线程")

感觉如何呀?虽然简单,但是还能实现的,欢迎大家交流,共同学习

18949050-b6fc-477e-8e69-6bcb270bc10b

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值