zoukankan      html  css  js  c++  java
  • python多线程示例1(工作太忙,仅仅作为记录)

     1 import threading
     2 
     3 # 多线程本质上是在一个 Python 程序里做的一个资源再分配,把几段代码的运行顺序进行先后调整达到 CPU 资源利用的最大化。
     4 
     5 # 直接继承线程类,然后覆盖继承类函数的方法
     6 class ThreadChild(threading.Thread):
     7     # 初始化 init: 通常继承线程类会扩写父类的初始化,来传递参数等。
     8     def __init__(self, times, name, ret_dic):
     9         # 扩写父类的初始化,首先调用父类的初始化
    10         threading.Thread.__init__(self)
    11         self.times = times
    12         self.name = name
    13         self.ret_dic = ret_dic
    14         return
    15 
    16     # 运行 run: 这是一个必须要覆盖的函数。启动线程调用的 start() 函数就是运行这个函数,这里是需要运行的核心代码。
    17     def run(self):
    18         # 覆盖重写函数 run
    19         for i in range(self.times):
    20             print(self.name + ' run: ' + str(i))
    21         self.ret_dic[self.name] = self.name + " finished with " + str(self.times) + " times printed"
    22         return
    23 
    24 
    25 if __name__ == '__main__':
    26 
    27     thread_pool = []
    28     ret_dic = {}
    29     th_1 = ThreadChild(times=3, name='th_1', ret_dic=ret_dic)
    30     th_2 = ThreadChild(times=5, name='th_2', ret_dic=ret_dic)
    31     thread_pool.append(th_1)
    32     thread_pool.append(th_2)
    33 
    34     # 非阻塞 start()
    35     for th in thread_pool:
    36         th.start()
    37     # 阻塞 join()
    38     for th in thread_pool:
    39         th.join()
    40 
    41     print(ret_dic)
    个人学习记录
  • 相关阅读:
    C#基础—string等类的有趣方法_1
    设计模式
    OOP-面向对象程序设计
    CSS3实用效果大全
    HTML5 DOM元素类名相关操作API classList简介(转载自张鑫旭大神)
    Js写的一个倒计时效果实例
    垂直居中的几种方案
    大图片加载优化解决方案
    DomReady实现策略
    脱离文档流
  • 原文地址:https://www.cnblogs.com/jeshy/p/15234052.html
Copyright © 2011-2022 走看看