• 线程的基本使用


    一、线程的概念:

      1、线程是进程中执行代码的一个分支,每个执行分支想要执行代码都需要CPU进行调度。即:线程是CPU调度的基本单位

      2、每个进程中至少要有一个线程,就是主线程。

    二、线程的作用

      实现多任务的一种方式。

    三、多线程的特点

      可以共享全局变量(因为在一个进程里)

    四、基本语法

      

      import threading

     

      子线程对象 = threading.Thread(target=函数)

      子线程对象.start()

      2、Thread类的参数:

        group: 线程组,目前只能使用None

        target: 执行的目录任务名

         name: 线程的名字

      给任务传递参数:

        args:  以元组的方式给执行的任务传递参数。

        kwargs:  以字典的方式给执行的任务传递参数。

      3、Thread类的常用方法

        start(): 启动(创建)子线程

        join():  等待子线程执行完结束

        terminate() : 不管任务是否完成,立马终止子线程。

     

     

    五、多线程的使用

      

    from threading import *
    from time import *
    
    
    def sing():
        sing_current_thread = current_thread()
        print("sing:", sing_current_thread)
    
        for i in range(3):
            print("唱歌中......")
            sleep(0.2)
    
    
    def dance():
        dance_current_thread = current_thread()
        print("dance:", dance_current_thread)
    
        for i in range(3):
            print("跳舞中.....")
            sleep(0.2)
    
    
    if __name__ == '__main__':
        main_current = main_thread()
        print("main:", main_current)
    
        t1 = Thread(target=sing,name="sing_current_thread")
        t2 = Thread(target=dance,name="dance_current_thread")
    
        t1.start()
        t2.start()
    View Code

    执行结果:

  • 相关阅读:
    jquery总结
    Reporting Services子报表
    Reporting Services分组及Toggle
    Reporting Services报表钻取
    Reporting Services环境
    两种很有用的组件
    Reporting Services正确显示页码
    Reporting Services发布
    Java面试题
    BigInteger引申的一个访问权限控制解决方案
  • 原文地址:https://www.cnblogs.com/yujiemeigui/p/14304813.html
Copyright © 2020-2023  润新知