码迷,mamicode.com
首页 > 编程语言 > 详细

Python 多线程

时间:2019-05-09 22:18:47      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:对象   方式   调用   isp   run   second   thread   查看   获得   

python中的线程实现

  python 的 thread 模块是比较底层的模块,threading 模块是对 thread 做了一些封装的,可以更好的使用

  说明:

  1. python的threading.Thread类有一个run方法,用于定义线程的功能函数,可以在自己的线程类中覆盖该方法。而创建自己的线程实例后,通过Thread类的start方法,可以启动该线程,交给python虚拟机进行调度,当该线程获得执行的机会时,就会调用run方法执行线程

  多线程执行

技术图片
# coding=utf-8
import threading
import time


class HelloWorld(threading.Thread):
    def run(self):
        print(f"hello, world ~, my name is{self.name}")
        time.sleep(1)


if __name__ == __main__:
    for i in range(5):
        hello_obj = HelloWorld()
        hello_obj.start()
View Code

  可以看到同时打印了 hello, world ~,还有自己的 name(Thread-id);当调用 start() 时,才会真正的创建线程,并且开始执行

  主线程会等待所有的子线程结束后才结束

技术图片
# coding=utf-8
import threading
import time


class HelloWorld(threading.Thread):
    def __init__(self, num):
        threading.Thread.__init__(self)
        self.second = num

    def run(self):
        print(f"hello, world ~, my name is{self.name}")
        time.sleep(self.second)


if __name__ == __main__:
    for i in range(5):
        hello_obj = HelloWorld(i)
        hello_obj.start()
    while True:
        # 查看当前运行的线程数量
        length = len(threading.enumerate())
        print(f"current running thread num is:{length}")
        if length <= 3:
            break
        time.sleep(1)
View Code

  总结:

    1. 每个线程默认有一个名字,尽管上面的例子中没有指定线程对象的name,但是python会自动为线程指定一个名字
    2. 当线程的run()方法结束时该线程完成
    3. 无法控制线程调度顺序,但可以通过别的方式来影响线程调度的方式

Python 多线程

标签:对象   方式   调用   isp   run   second   thread   查看   获得   

原文地址:https://www.cnblogs.com/kaichenkai/p/10841008.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!