0
点赞
收藏
分享

微信扫一扫

Python多线程编程threading类


Python多线程编程threading类

方式一

使用python自带的线程类threading创建线程:

import threading
import time


def thread_1_entry(count):
while count > 0:
print('count:%d' % count)
count -= 1
time.sleep(1)
return


def thread_2_entry():
print(threading.current_thread().name)
return


'''创建线程参数说明:
target:线程入口函数
name :线程名称
args : 线程入口函数的参数
'''
thread_1 = threading.Thread(target=thread_1_entry, name='thread 1', args=(5,))
thread_2 = threading.Thread(target=thread_2_entry, name='thread 2')

# 启动线程
thread_1.start()
thread_2.start()

# 等待线程执行完毕退出
thread_1.join()
thread_2.join()

执行结果:

Python多线程编程threading类_多线程

方式二

继承threading类,覆写run函数:

import threading
import time


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

def run(self):
count = 5
while count > 0:
print('%s:%d' % (self.name, count))
count -= 1
time.sleep(1)


mythread_1 = MyThread(name='MyThread-ONE')
mythread_2 = MyThread(name='MyThread-TWO')

mythread_1.start()
mythread_2.start()

mythread_1.join()
mythread_2.join()

执行结果:

Python多线程编程threading类_多线程_02

ends…


举报

相关推荐

0 条评论