看漫画学Python 第十六章代码

本文通过漫画形式,详细讲解了Python中的线程模块threading,包括如何自定义函数和线程类实现线程体,以及如何等待线程结束和停止线程。还提供了一个下载图片的线程应用实例。

16.2 线程模块threading

import threading
#当前线程对象
t = threading.current_thread()
#当前线程名
print(t.name)

#返回当前处于活动状态的线程个数
print(threading.active_count())

#当前主线程对象
t = threading.main_thread()
#主线程名
print(t.name)

16.3.1 自定义函数实现线程体

import threading
import time

#线程体函数
def thread_body():
	#当前线程对象
	t = threading.current_thread()
	for n in range(5):
		#当前线程名
		print("第{0}次执行线程{1}".format(n,t.name))
		#线程休眠
		time.sleep(2)
	print("线程{0}执行完成!".format(t.name))

#主线程
#创建线程对象t1
t1 = threading.Thread(target = thread_body)
#创建线程对象t2
t2 = threading.Thread(target = thread_body,name = "MyThread")
#启动线程t1
t1.start()
#启动线程t2
t2.start()

16.3.2 自定义线程类实现线程体

import threading
import time

class SmallThread(threading.Thread):
	def __init__(self,name = None):
		super().__init__(name = name)
	#线程体函数
	def run(self):
		#当前线程对象
		t = threading.current_thread()
		for 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值