victory的博客

长安一片月,万户捣衣声

0%

多线程 | 实现线程体的两种方式

实现线程体的两种方式

实现线程体主要有以下两种方式:
1.自定义函数实现线程体
代码实例:

# coding=utf-8

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

2.自定义线程类实现线程体
代码实例:

# coding=utf-8

import time
import threading


class SmallThread(threading.Thread):
    def __init__(self, name=None):
        super().__init__(name=name)

    # 线程体函数
    def run(self):
        # 当前线程对象
        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 = SmallThread()  # 通过自定义线程类,创建线程对象
# 创建线程对象t2
t2 = SmallThread(name='MyThread')
# 启动线程t1
t1.start()
# 启动线程t2
t2.start()