zoukankan      html  css  js  c++  java
  • Python线程的用法 函数式线程_thread和threading 样例

    函数式线程写起来比较简单,但是功能没有threading那么高级,先来个函数式编程样例:

    #!/usr/bin/python
    #coding: utf-8
    
    
    #————————————————————————函数式线程————————————————————————————————————————
    #QQ496631085  小和   XiaoHe
    import _thread
    import time
    
    def     print_time(threadName,delay):
        count = 0
        while count<4:
            time.sleep(delay)
            count += 1
            print(threadName,time.ctime())
    
    print(time.ctime())#打印现在时间以方便对比
    _thread.start_new_thread(print_time,("thread-1",2))
    _thread.start_new_thread(print_time,("thread-2",4))
    time.sleep(200)#不加这个有的编译器,直接到最后就停止整个程序运行了,看不出效果
    print("end")
    
    #————————————————————————函数式线程————————————————————————————————————————

    然后就是threading线程样例:

    #!/usr/bin/python
    #coding: utf-8
    
    
    
    #===========================threading========================================
    
    #QQ496631085  XiaoHe
    import threading
    import time
    
    class myThread(threading.Thread):
        """docstring for myThread"""
        def __init__(self, name,delay):
            threading.Thread.__init__(self)
            print(name+"线程开始时间" +time.ctime())
    
            self.name =name
            self.delay = delay
    
        def run(self):
            print("Starting " + self.name + time.ctime())
            print_time(self.name, self.delay)
            print("Exiting " + self.name + time.ctime())
    
    def print_time(threadName, delay):
        counter = 0
        while counter < 3:
            time.sleep(delay)
            print("延时" + threadName  ,time.ctime())
            counter+=1
    
    
    
    threads =[]
    #创建新线程
    thread1= myThread("Thread-111",2)
    thread2= myThread("Thread-222",4)
    
    #开始新线程
    thread1.start()
    thread2.start()
    
    #添加线程到线程列表   然后一直等待线程终止
    threads.append(thread1)
    threads.append(thread2)
    
    #等待线程结束
    for t in threads:
        t.join()
    print("线程结束")
    #===========================threading========================================

     如果觉得这个还慢有不足的地方,可以试试queue的多线程爬虫

  • 相关阅读:
    CF432D Prefixes and Suffixes
    CF126B Password
    如何实现输入历史记录功能
    python工作中总结
    今 天看到我十年前的一篇技术文章,想到不知不觉学编程十多年了,,
    现在互联网好多bug 想到都烦
    【图论】割点
    【DP】【P1941】【NOIP2014D1T3】飞扬的小鸟
    【线段树】【P3740】 [HAOI2014]贴海报
    【单调队列】【P1714】 切蛋糕
  • 原文地址:https://www.cnblogs.com/xiaohe520/p/10767361.html
Copyright © 2011-2022 走看看