Python线程之多线程展示详解

来自:网络
时间:2022-01-08
阅读:
目录

什么多线程?

多线程,就是多个独立的运行单位,同时执行同样的事情。

想想一下,文章发布后同时被很多读者阅读,这些读者在做的事情‘阅读'就是一个一个的线程。
多线程就是多个读者同时阅读这篇文章。重点是:同时有多个读者在做阅读这件事情。

如果是多个读者,分时间阅读,最后任意时刻只有一个读者在阅读,虽然是多个读者,但还是单线程。

我们再拿前面分享的代码:关注和点赞。

def dianzan_guanzhu():
    now = datetime.datetime.now()
    name = "python萌新"
    print("%s name:%s" % (now, name))
    time.sleep(1)
    result = "好棒!" + name + " 关注雷学委,学会了开发知识!"
    print("%s result:%s" % (now, result))
    return result

我们看看下面的代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/21 12:02 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
import threading
import datetime
import time
def dianzan_guanzhu():
    now = datetime.datetime.now()
    name = "python萌新"
    print("%s name:%s" % (now, name))
    time.sleep(1)
    result = "好棒!" + name + " 关注雷学委,学会了开发知识!"
    print("%s result:%s" % (now, result))
    return result
for i in range(3):
    mythread = threading.Thread(name="t-" + str(i), target=dianzan_guanzhu)
    print("mythread:", mythread)
    print("is_alive:", mythread.is_alive())
    mythread.start()
    print("is_alive:", mythread.is_alive())

Thread类可以传入name指定线程名字。

直接复制运行,这里我们创建了3个线程。

它们依次调用了dianzan_guanzhu函数

下面是运行结果:

Python线程之多线程展示详解

这3个线程不同时间打印完成了,但是内容打印乱序了,甚至还串行了。

读者同学可以多运行几次。

获取活跃线程相关数据

  • threading.active_count函数: 可以获取活跃线程数。
  • threading.current_thread函数:可以获取活跃线程对象,这样我们可以获取这样获取线程名称:threading.current_thread().getName()。

前文说过了,加上主线程,一共是4个线程。

运行下面代码看看:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/11/21 12:02 上午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷学委
# @XueWeiTag: CodingDemo
# @File : __init__.py.py
# @Project : hello
import random
import threading
import datetime
import time
def dianzan_guanzhu():
    thread_name = threading.current_thread().getName()
    now = datetime.datetime.now()
    print("线程启动了:", thread_name)
    name = "python萌新"+thread_name
    print("%s - %s name:%s" % (thread_name, now, name))
    time.sleep(1)
    result = "好棒!" + name + " 关注雷学委,学会了开发知识!"
    print("%s - %s result:%s" % (thread_name, now, result))
    return result
for i in range(3):
    mythread = threading.Thread(name="t-" + str(i), target=dianzan_guanzhu)
    print("mythread:", mythread)
    print("is_alive:", mythread.is_alive())
    mythread.start()
    ac = threading.active_count()
    print("active_count:", ac)

如果我们把活跃线程数打印,那么等3个线程都start调用了。

加上主线程,最多是4个活跃线程。

Python线程之多线程展示详解

今天先展示一下多个线程执行同个任务的代码实现。

总结

本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注的更多内容!

返回顶部
顶部