- 开发工具
- 知识点
- 代码
- 总结
- python版本: python-3.8.1-amd64
- python开发工具: JetBrains PyCharm 2018.3.6 x64
代码多线程
网络编程
# coding = utf-8
import threading
import time
import urllib.request
# 线程停止变量
isrunning = True
# 工作线程体函数
def workthread_body():
while isrunning:
# 线程开始工作
print('工作线程执行下载任务...')
# 下载任务每5秒调用一次
download()
# 线程休眠
time.sleep(5)
print('工作线程执行完成!')
# 控制线程体函数
def controlthread_body():
global isrunning
while isrunning:
# 从键盘输入停止指令exit
command = input("请输入停止指令: ")
if command == 'exit':
isrunning = False
print('控制线程结束')
def download():
# 地址可以换成任意一个网络图片地址
url = 'https://gimg2.baidu.com/image_search/src=https://www.mshxw.com/skin/sinaskin/image/nopic.gif'
req = urllib.request.Request(url)
with urllib.request.urlopen(url) as response:
data = response.read()
f_name = 'download.png'
with open(f_name, 'wb') as f:
f.write(data)
print('下载文件成功')
pass
# 主线程
# 创建工作线程对象workthread
workthread = threading.Thread(target=workthread_body)
# 启动线程workthread
workthread.start()
# 创建工作线程对象controlthread
controlthread = threading.Thread(target=controlthread_body)
# 启动线程controlthread
controlthread.start()
总结
多线程中,可以利用两个线程控制一个全局变量,实现一个线程对另一个线程的停止



