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
  • 相关阅读:
    Eclipse 导入项目乱码问题(中文乱码)
    sql中视图视图的作用
    Java基础-super关键字与this关键字
    Android LayoutInflater.inflate(int resource, ViewGroup root, boolean attachToRoot)的参数理解
    Android View和ViewGroup
    工厂方法模式(java 设计模式)
    设计模式(java) 单例模式 单例类
    eclipse乱码解决方法
    No resource found that matches the given name 'Theme.AppCompat.Light 的完美解决方案
    【转】使用 Eclipse 调试 Java 程序的 10 个技巧
  • 原文地址:https://www.cnblogs.com/sunzebo/p/9607760.html
Copyright © 2011-2022 走看看