zoukankan      html  css  js  c++  java
  • [b0024] python 归纳 (十)_线程 _Thread模块

     
    #!/usr/bin/pythonn
    # -*- coding: UTF-8 -*-
    """
    学习线程  thread
    总结:
        1.  主线程退出,所有子线程都退出
        2.  子线程 能直接读取外部变量
        3.  thread.start_new_thread 调用后,立即执行并发代码了,不像有些模块,执行完后,要调用start方法才执行并发代码,xxxx.yyyy().start()
    
    使用:
        调用 thread.start_new_thread( <func>,(parmas,parmas))
        根据上述 第一条 原则,看情况是否在 启动 线程后 ,主线程代码如何处理
    """
    import thread
    import time
    import threading
    
    a = 0  #  不同线程共同操作数据
    def print_time(threadname,delay):
        global a
        print "thread %s,%s start" % (threading.currentThread().getName(),threadname)
        count = 0
        while count <3:
            time.sleep(delay)
            count +=1
            a +=1
            print "%d,%s,%s:%s" % (a,threading.currentThread().getName(),threadname,time.ctime(time.time()) )
    
        print "thread %s,%s end" % (threading.currentThread().getName(),threadname)
    
    print "main:%s  start"  %  threading.currentThread().getName()
    
    try:
        thread.start_new_thread(print_time,("thread1",2,))
        thread.start_new_thread(print_time,("thread2",3,))
    except:
        print "Error: unable to start thread"
        pass
    
    time.sleep(7)
    print "main:%s  end" %  threading.currentThread().getName()

    输出:

    主线程等所有子线程跑完
    time.sleep(15)
    
    Out:
    main:MainThread  start
    thread Dummy-1,thread1 start
    thread Dummy-2,thread2 start
    1,Dummy-1,thread1:Sat Sep 08 02:23:04 2018
    2,Dummy-2,thread2:Sat Sep 08 02:23:05 2018
    3,Dummy-1,thread1:Sat Sep 08 02:23:06 2018
    4,Dummy-2,thread2:Sat Sep 08 02:23:08 2018
    5,Dummy-1,thread1:Sat Sep 08 02:23:08 2018
    thread Dummy-1,thread1 end
    6,Dummy-2,thread2:Sat Sep 08 02:23:11 2018
    thread Dummy-2,thread2 end
    main:MainThread  end
    
    ---------------------------------------------------
    主线程没有等子线程跑完 ,自己先跑完
    time.sleep(7)
    Out:
    main:MainThread  start
    thread Dummy-1,thread1 start
    thread Dummy-2,thread2 start
    1,Dummy-1,thread1:Sat Sep 08 02:25:29 2018
    2,Dummy-2,thread2:Sat Sep 08 02:25:30 2018
    3,Dummy-1,thread1:Sat Sep 08 02:25:31 2018
    4,Dummy-1,thread1:Sat Sep 08 02:25:33 2018
    thread Dummy-1,thread1 end
    5,Dummy-2,thread2:Sat Sep 08 02:25:33 2018
    
    main:MainThread  end
  • 相关阅读:
    80x86的保护模式
    计算机二进制的表示
    操作系统基本知识(一)
    记录一次在安装双系统的过程(先有debian, 后加windows 8.1)
    LitePal + Gson + Volley的ORM框架尝试方案
    如何使用DDMS Heap查看Android应用内存情况
    测试驱动开发的第一个例子---我的毕业设计
    策略模式的孪生兄弟---状态模式
    面试常备---栈和队列总结篇
    面试常备题---二叉树总结篇
  • 原文地址:https://www.cnblogs.com/sunzebo/p/9607760.html
Copyright © 2011-2022 走看看