Python多线程练习(threading)

这几天学习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 
')%(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]
欢迎来邮件交流:lq65535@163.com
原文地址:https://www.cnblogs.com/lq1024/p/7593644.html