Python之多线程(三)实现一个线程

释放双眼,带上耳机,听听看~!

线程的两种实现方式

一:、使用def(方法)方式来实现

先 import 我们的模块:

import threding
import time    # 延时模块

建一个线程需要执行的代码:

def loop():
    """ 新的线程执行的代码 """
    now_thread = threading.current_thread()
    n = 0
    while n < 5:
        print(n)
        print('[loop]now thread name:{0}'.format(now_thread.name))
        time.sleep(1)    # 在给定的秒数内暂停调用线程的执行。参数:秒
        n += 1

使用线程来实现:

def use_thread():
    """ 使用线程来实现 """
    # 当前正在执行的线程名称
    now_thread = threading.current_thread()     # 返回调用线程的对象
    print('now thread name:{0}'.format(now_thread.name))    # .name线程名
    t = threading.Thread(target=loop, name='loop_thread'    
    # 启动线程
    t.start()
    # 挂起线程
    t.join()

测试代码:

if __name__ == '__main__'
use_thread()

完整代码:

import threading
import time


def loop():
    """ 新的线程执行的代码 """
    now_thread = threading.current_thread()
    n = 0
    while n < 5:
        print(n)
        print('[loop]now thread name:{0}'.format(now_thread.name))
        time.sleep(1)   # 在给定的秒数内暂停调用线程的执行。参数:秒
        n += 1


def use_thread():
    """ 使用线程来实现 """
    # 当前正在执行的线程名称
    now_thread = threading.current_thread()     # 返回调用线程的对象
    print('now thread name:{0}'.format(now_thread.name))    # .name线程名
    # 设置线程
    t = threading.Thread(target=loop, name='loop_thread')
    # 启动线程
    t.start()
    # 挂起线程
    t.join()


if __name__ == '__main__':
    use_thread()

执行以上程序的结果:

now thread name:MainThread
0
[loop]now thread name:loop_thread
1
[loop]now thread name:loop_thread
2
[loop]now thread name:loop_thread
3
[loop]now thread name:loop_thread
4
[loop]now thread name:loop_thread

二:、使用class(类)方式来实现

import threading
import time
class LoopThread(threading.Thread):
    """ 自定义线程 """
    n = 0

    def run(self):
        while self.n < 5:
            print(self.n)
            now_thread = threading.current_thread()
            print('[loop]now thread name:{0}'.format(now_thread.name))
            time.sleep(1)  # 在给定的秒数内暂停调用线程的执行。参数:秒
            self.n += 1


if __name__ == '__main__':
# 当前正在执行的线程名称
now_thread = threading.current_thread()
print('now thread name:{0}'.format(now_thread.name))
t = LoopThread(name='loop_thread')
t.start()
t.join()

执行以上程序的结果:

now thread name:MainThread
0
[loop]now thread name:loop_thread
1
[loop]now thread name:loop_thread
2
[loop]now thread name:loop_thread
3
[loop]now thread name:loop_thread
4
[loop]now thread name:loop_thread

 

 

 

人已赞赏
0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧