zoukankan      html  css  js  c++  java
  • threading示例

    多线程举例:

    import time
    import threading
    def worker():
        print ("hello.Kamil")
        time.sleep(1)#等待一秒
        return
    time_start=time.time()
    if __name__ == "__main__":
        for i in range(5):
            worker()#(执行五次)
    time_end = time.time()
    print(time_end-time_start)
    for n in range(5):
        t = threading.Thread(target=worker)
        t.start()
    time_end2 = time.time()

    执行结果:

    kamil@ubuntu-kamil:~/PycharmProjects/ftp0310/0310shangke/try$ python3.4 d.py 
    hello.Kamil
    hello.Kamil
    hello.Kamil
    hello.Kamil
    hello.Kamil
    5.006033897399902
    hello.Kamil
    hello.Kamil
    hello.Kamil
    hello.Kamil
    hello.Kamil
    0.0030531883239746094
    kamil@ubuntu-kamil:~/PycharmProjects/ftp0310/0310shangke/try$ 

    第二次虽然也是循环5次,但是启用多线程来完成的,所以速度提升非常明显;

    示例2:

    import threading
    import time
    class timer(threading.Thread):
        def __init__(self, num, interval):
            threading.Thread.__init__(self)
            self.thread_num = num
            self.interval = interval
            self.thread_stop = False
        def run(self):
            while not self.thread_stop:
                print ('Thread Object(%s), Time:%s
    ' %(self.thread_num, time.ctime())  )
                time.sleep(self.interval)
        def stop(self):
            self.thread_stop = True
    def test():
        thread1 = timer('thread1',2)
        thread2 = timer('thread2',3)
        thread1.start()
        thread2.start()
        time.sleep(7)
        thread1.stop()
        thread2.stop()
        return
    
    if __name__ == '__main__':
        test()

    同时启动两个线程,thread1 与 thread2 ,其中1 是间隔2s 执行打印一次,2是间隔3s执行打印一次;在运行开始后,会在第六秒再次同时运行;结果如下:

    kamil@ubuntu-kamil:~/PycharmProjects/ftp0310/0310shangke/try$ python3.4 c.py 
    Thread Object(thread1), Time:Thu Mar 17 09:27:26 2016                      1   26
    
    Thread Object(thread2), Time:Thu Mar 17 09:27:26 2016                      2   26
    
    Thread Object(thread1), Time:Thu Mar 17 09:27:28 2016             1   28
    
    Thread Object(thread2), Time:Thu Mar 17 09:27:29 2016                      2   29
    
    Thread Object(thread1), Time:Thu Mar 17 09:27:30 2016                      1   30
    
    Thread Object(thread2), Time:Thu Mar 17 09:27:32 2016                      2   32
    
    Thread Object(thread1), Time:Thu Mar 17 09:27:32 2016                      1   32
    
    kamil@ubuntu-kamil:~/PycharmProjects/ftp0310/0310shangke/try$ 

     threading.activeCount()的使用

    公众号请关注:侠之大者
  • 相关阅读:
    JMeter
    MeasureSpec介绍及使用详解
    AS中一些不经常用到的快捷键
    gradle 构建工具,与Ant Maven关系
    关于runOnUiThread()与Handler两种更新UI的方法
    关于new Handler()与new Handler(Looper.getMainLooper())区别
    RTSP协议详解
    overridePendingTransition的简介
    Android获取手机分辨率DisplayMetircs类
    RTSP消息交互过程
  • 原文地址:https://www.cnblogs.com/kamil/p/5286026.html
Copyright © 2011-2022 走看看