• Python多线程


    多线程技术需。要用到threading模块,应当避免使用thread模块,原因是它不支持守护线程。当主线程退出时,所有的子线程不管他们是都还在工作,都会被强制退出。有时候我们并不希望发生这种行为

    ,这时候就需要引入守护线程的概念。 threading模块支持守护线程,所以在需要使用多线程的时候,直接使用threading模块就行。

     1 #coding:utf-8
     2 import sys
     3 reload(sys)
     4 sys.setdefaultencoding('utf8')
     5 from time import sleep,ctime
     6 import threading
     7 
     8 #音乐播放器
     9 def music(func,loop):
    10     for i in range(loop):
    11         print (' I was listening to %s! %s' % (func,ctime()))
    12         sleep(2)
    13 
    14 
    15 #视频播放器
    16 def movie(func,loop):
    17     for i in range(loop):
    18         print('I was at the %s! %s' % (func,ctime()))
    19         sleep(5)
    20 
    21 #创建线程数组
    22 threads = []
    23 
    24 #创建线程t1,并添加到线程数组
    25 t1 = threading.Thread(target=music,args=('爱情买卖',2))
    26 threads.append(t1)
    27 
    28 #创建线程t2,并添加到线程数组
    29 t2 = threading.Thread(target=movie,args=('阿凡达',2))
    30 threads.append(t2)
    31 
    32 if __name__ == "__main__":
    33     #启动线程
    34     for t in threads:
    35         t.start()
    36     #守护线程
    37     for t in threads:
    38         t.join()
    39     print ('all end:%s' % ctime())

    import threading  :  引入线程模块

    threads = 【】:  创建线程数组,用于装载线程

    threading.Thread():  通过调用threading模块下的Thread()方法来创建线程。

    通过for循环遍历threads数组中所装载的线程;start()开始线程活动,join()等待线程终止。

    I was listening to 爱情买卖! Thu Dec 21 14:07:58 2017
    I was at the 阿凡达! Thu Dec 21 14:07:58 2017
    I was listening to 爱情买卖! Thu Dec 21 14:08:00 2017
    I was at the 阿凡达! Thu Dec 21 14:08:03 2017
    all end:Thu Dec 21 14:08:08 2017

    从上面运行的结果来看 两个子线程同时启动14:07 总共用时10秒,两个电影循环总共消耗10秒,两个音乐总共消耗4秒 可以看到达到了并行工作的效果。

  • 相关阅读:
    GNU计划的起因及其现状
    【KVM新概念】 虚拟机CPU热拔插
    Amazon vs Google 云服务
    【笨木头Cocos2dx 039】战争迷雾效果 第02章_先把地图加进来
    【C++11】新特性——auto的使用
    Netty4 SEDA 事件驱动原理分析
    error ,exception
    Compiling Java with makefile
    (二)Centos7下Yum更新安装PHP5.5,5.6,7.0
    CentOS7.0下安装FTP服务的方法
  • 原文地址:https://www.cnblogs.com/stephenmc/p/8081125.html
Copyright © 2020-2023  润新知