Python多线程练习(threading)

本文对比了Python中thread和threading模块的使用体验,推荐使用threading模块进行多线程编程,并提供了两种实用的多线程实现方式:通过直接实例化Thread类及通过自定义线程类并重写run方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这几天学习python多线程的时候,试了几次thread模块和threading模块,发现thread模块非常的不好用。强烈不建议大家使用thread,建议使用threading模块,此模块对thread进行了封装,而且还加入了其他的一些方法,比如同步机制,程序员不用考虑主线程退出去的时候其他子线程也强制退出去,不说了上代码

# *_* coding:utf-8 *_*

import time
import threading

def a():
    print ('now a start running:'),time.ctime()
    time.sleep(5)
    print ('a is ending:'),time.ctime()


def b():
    print ('now b start running:'),time.ctime()
    time.sleep(10)
    print ('b is ending:'),time.ctime()


def test():
    a1 = threading.Thread(target=a,args=()) #实例化线程
    b1 = threading.Thread(target=b, args=())
    p = [a1,b1]  
    for i in range(len(p)):  #启动多线程
        p[i].start()
    for i in range(len(p)):  #join()方法等待每一个线程结束
        p[i].join()
test()

执行结果:

now a start running: Wed May 17 09:59:17 2017
now b start running: Wed May 17 09:59:17 2017
a is ending: Wed May 17 09:59:22 2017
b is ending: Wed May 17 09:59:27 2017
[Finished in 10.3s]

方法二,写一个类继承threading,重写run方法,举例:

# *_* coding:utf-8 *_*

import threading as th 
from time import *

class test(th.Thread):
    def __init__(self,args):
        super(test,self).__init__()
        self.args = args

    def run(self):
        print ('the %s is running')%th.currentThread().getName()
        sleep(2)
        print self.args
        print ('the %s has done at %s \n')%(th.currentThread().getName(),ctime()) #返回当前线程变量的名字
tread = []

for i in range(4):
    t = test(i)
    tread.append(t)

for p in tread:
    p.setDaemon(True)
    p.start()

for n in tread:
    n.join()

print ('all has done!')

#执行结果

# the Thread-1 is running
# the Thread-2 is running
# the Thread-3 is running
# the Thread-4 is running
# 3
# the Thread-4 has done at Wed May 24 16:48:00 2017 

# 2
# 10

# the Thread-1 has done at Wed May 24 16:48:00 2017 
# the Thread-2 has done at Wed May 24 16:48:00 2017 


# the Thread-3 has done at Wed May 24 16:48:00 2017 

# all has done!
# [Finished in 2.4s]

转载于:https://www.cnblogs.com/lq1024/p/7593644.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值