当前位置:   article > 正文

Python多线程练习(threading)_python 多线程练习

python 多线程练习

这几天学习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()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

执行结果:

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]
  • 1
  • 2
  • 3
  • 4
  • 5

方法二,写一个类继承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]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/768805
推荐阅读
相关标签
  

闽ICP备14008679号