victory的博客

长安一片月,万户捣衣声

0%

多线程 | 线程停止

线程停止

在线程体结束时,线程就停止了。但在某些业务比较复杂时,会在线程体重执行一个“死循环”。线程体是够执行“死循环”是通过
判断停止变量实现的,“死循环”结束则线程体结束,线程也就结束了。

示例代码:

# coding=utf-8

import time
import threading

# 线程停止变量
isrunning = True


# 工作线程体函数
def workthread_body():
    while isrunning:
        # 线程开始工作
        print('工作线程执行中...')
        # 线程休眠
        time.sleep(5)
    print('工作线程结束。')


# 控制线程体函数
def controlthread_body():
    global isrunning
    while isrunning:
        # 从键盘输入停止指令exit
        command = input('请输入停止指令:')
        if command == 'exit':
            isrunning = False
            print('控制线程结束')


# 主线程
# 创建工作线程对象workthread
workthread = threading.Thread(target=workthread_body)
# 启动线程workthread
workthread.start()

# 创建控制线程对象controlthread
controlthread = threading.Thread(target=controlthread_body)
# 启动线程controlthread
controlthread.start()