• 多线程的简单演示


    一、前言

      我们知道单核cpu同时只能执行一个任务。如果在一个单核cpu的电脑上,我们可以同时登入qq、听音乐或者写文档等,给我们的感觉它们就是同时在进行的。这是由于cpu的分时技术,使它不断的进行上下文的切换,根据任务的优先级不停的在各个任务间切换执行。而且由于cpu运行太快,我们根本感觉不到它在切换任务,所以就给了我们同时在执行多个任务。

    二、简单的多线程并发

      2.1 创建线程 

    import threading   # 线程模块
    
    
    # 定义每个线程要运行的函数
    def run(n):
        print('task', n)
    
    
    if __name__ == '__main__':
    
        # 生成一个线程实例 , 参数为 元组形式
        t1 = threading.Thread(target=run, args=("t1",))
        # 生成另一个线程实例 , 参数为 元组形式
        t2 = threading.Thread(target=run, args=("t2",))
    
       # 启动线程
        t1.start()
        t2.start()    
    

      2.2 对比运行

      好像运行结果除了同时出来外,没什么特别的,我们稍稍修改一下

      

    import threading
    import time
    
    
    def run(n):
        print('task', n)
        time.sleep(2)
    
    if __name__ == '__main__':
    
        t1 = threading.Thread(target=run, args=("t1",))
        t2 = threading.Thread(target=run, args=("t2",))
        # t1.start()
        # t2.start()
    
        run('t1')
        run('t2')
    

      我们让程序sleep一会,就能很明显看出并发运行的效果了

     三、继承式调用

      上面使用线程方法可以被称为直接调用,而继承式调用需要我们自己写一个类,继承threading.Thread

      方法:

    1. 先定义一个类,继承threading.Thread
    2. 要继承父类的构造函数
    3. 定义一个运行的函数,必须是 run()
    import threading
    import time
    
    
    class MyThread(threading.Thread):
    
        def __init__(self, n):
            super(MyThread, self).__init__()
            self.n = n
    
        def run(self):
            print('task', self.n)
            time.sleep(2)
    
    if __name__ == '__main__':
        t1 = MyThread(1)
        t2 = MyThread(2)
    
        t1.start()
        t2.start()
    

      

  • 相关阅读:
    小白学开发(iOS)OC_ 使用继承来扩充类(2015-08-07)
    UI组件之TextView及其子类(三)ToggleButton和Switch
    C++智能指针--shared_ptr
    HDU 1013 Digital Roots 题解
    对touch事件传递的简单理解
    【LeetCode-面试算法经典-Java实现】【096-Unique Binary Search Trees(唯一二叉搜索树)】
    Cocos2d-x 坐标系
    hdu1518 Square
    servlet3.0新特性
    OGNL表达式
  • 原文地址:https://www.cnblogs.com/bigberg/p/7810955.html
Copyright © 2020-2023  润新知