两种线程创建方式

  • 类继承
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/17 11:34
# @Author  : 波澜不惊
# @File    : threading模块创建线程.py
# threading模块提供的方法:
# threading.currentThread() -返回当前的线程变量
# threading.enumerate() -返回一个包含正在运行的线程的list.
# 正在运行 -指线程启动后、结束前,不包括启动前和终止后的线程.
# threading.activeCount -返回正在运行的线程数量,和len(threading.enumerate())有相同的结果
# 除了使用方法外,线程模块同样提供了Thread类来处理线程,Thread类提供了下列方法:
# run() -用以表示线程活动的方法
# start() -启动线程活动
# join([time]) -等待至线程中止.
# 这阻塞调用线程直至线程的join()方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生
# isAlive() -返回线程是否活动
# getName() -返回线程名
# setName() -设置线程名

import threading
import time


exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay

    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name, self.delay, 5)
        print("退出线程:" + self.name)


def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print("%s: %s" %(threadName, time.ctime(time.time())))
        counter -= 1


#   创建新线程
thread1 = myThread(1, "T1", 1)
thread2 = myThread(2, "T2", 2)


# 开启线程
thread1.start()
thread2.start()
thread1.join()      # 这里需要注意join()守护线程
thread2.join()      # 让主线程进入阻塞等待thread1、thread2执行完毕,主线程再结束
print("退出主线程")

---执行结果----------------------------------------------
开始线程:T1
开始线程:T2
T1: Mon Jan 17 21:09:16 2022
T2: Mon Jan 17 21:09:17 2022
T1: Mon Jan 17 21:09:17 2022
T1: Mon Jan 17 21:09:18 2022
T2: Mon Jan 17 21:09:19 2022
T1: Mon Jan 17 21:09:19 2022
T1: Mon Jan 17 21:09:20 2022
退出线程:T1
T2: Mon Jan 17 21:09:21 2022
T2: Mon Jan 17 21:09:23 2022
T2: Mon Jan 17 21:09:25 2022
退出线程:T2
退出主线程

进程已结束,退出代码为 0

需要注意A.join()方法,它的作用通俗来说就是让主线程等待A线程执行完毕,在此之前主线程会陷入阻塞状态,当A线程结束后才会继续运行

  • 函数式创建线程
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/16 23:14
# @Author  : 波澜不惊
# @File    : 线程创建实例.py
# 函数式创建线程:调用_thread模块中的start_new_thread()函数来产生新线程
# _thread.start_new_thread ( function, args[ , kwargs ])
# function -线程函数
# args -传递给线程函数的参数,它必须是个tuple类型
# kwargs -可选参数

import _thread
import time


# 为线程定义一个函数
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("%s: %s" % (threadName, time.ctime(time.time())))


# 创建两个线程
try:
    _thread.start_new_thread(print_time, ("T1", 2))
    _thread.start_new_thread(print_time, ("T2", 4))
except Exception:
    print("Error: 无法启动线程")


while 1:
    pass    # 保持主线程不结束
---执行结果-------------------------------------
T1: Mon Jan 17 21:07:27 2022
T2: Mon Jan 17 21:07:29 2022
T1: Mon Jan 17 21:07:29 2022
T1: Mon Jan 17 21:07:31 2022
T2: Mon Jan 17 21:07:33 2022
T1: Mon Jan 17 21:07:33 2022
T1: Mon Jan 17 21:07:35 2022
T2: Mon Jan 17 21:07:37 2022
T2: Mon Jan 17 21:07:41 2022
T2: Mon Jan 17 21:07:45 2022

线程同步

获取锁,用于线程同步

threadLock.acquire()

释放锁,开启下一个线程

threadLock.release()

# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/17 12:16
# @Author  : 波澜不惊
# @File    : 线程同步.py
# 当线程共享数据时,可能会导致数据不同步的情况出现
# 为了避免数据的不同步,引入了锁的概念
# 锁有两种状态,锁定和未锁定.当一个线程A要访问共享数据D时,必须先获得锁定;
# 如果此时已经有别的线程B获得锁定了,那么线程A就要进入阻塞状态;
# 等待B访问完毕,释放锁之后,线程A才能继续使用并锁定共享数据D
import threading
import time


class myThread(threading.Thread):
    def __init__(self, threadID, name, delay):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.delay = delay

    def run(self):
        print("开启线程:" + self.name)
        # 获取锁,用于线程同步
        threadLock.acquire()
        print_time(self.name, self.delay, 3)
        # 释放锁,开启下一个线程
        threadLock.release()


def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


threadLock = threading.Lock()
threads = []

# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# 开启新线程
thread1.start()
thread2.start()

# 添加线程到线程列表
threads.append(thread1)
threads.append(thread2)

# 等待所有线程完成
for t in threads:
    t.join()
print("退出主线程")
---执行结果-------------------------------------------
开启线程:Thread-1
开启线程:Thread-2
Thread-1: Mon Jan 17 21:16:21 2022
Thread-1: Mon Jan 17 21:16:22 2022
Thread-1: Mon Jan 17 21:16:23 2022
Thread-2: Mon Jan 17 21:16:25 2022
Thread-2: Mon Jan 17 21:16:27 2022
Thread-2: Mon Jan 17 21:16:29 2022
退出主线程

进程已结束,退出代码为 0

线程优先级队列Queue

Java的线程优先级通过级数就能设置,不要太方便, python的这个更偏向于队列,一个实现了线程安全、线程同步的线程执行队列
# !/usr/bin/env pythonQueue
# -*- coding: utf-8 -*-
# @Time    : 2022/1/17 13:51
# @Author  : 波澜不惊
# @File    : 线程优先级.py
# 线程优先级队列(Queue)
# 常用方法:
# Queue.qsize() -返回队列的大小
# Queue.empty() -如果队列为空,返回True,反之False
# Queue.full() -如果队列满了,返回True,反之false
# Queue.full与maxsize大小对应
# Queue.get([block[, timeout]])获取队列,timeout等待时间
# Queue.get_nowait()相当于Queue.get(False)
# Queue.put(item)写入队列,timeout等待时间
# Queue.put_nowait(item)相当于Queue.put(item,False)
# Queue.task_done()在完成一项工作之后,Queue.task_done()函数向任务已经完成的队列发送一个信号
# Queue.join()实际上意味着等到队列为空,再执行别的操作

import queue
import threading
import time

exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, q):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.q = q

    def run(self):
        print("开启线程:" + self.name)
        process_data(self.name, self.q)
        print("退出线程:" + self.name)


def process_data(threadName, q):
    while not exitFlag:
        queueLock.acquire()
        if not workQueue.empty():
            data = q.get()
            queueLock.release()
            print("%s processing %s" % (threadName, data))
        else:
            queueLock.release()
        time.sleep(1)


threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = queue.Queue(10)
threads = []
threadID = 1

# 创建新线程
for tName in threadList:
    thread = myThread(threadID, tName, workQueue)
    thread.start()
    threads.append(thread)
    threadID += 1

# 填充队列
queueLock.acquire()
for word in nameList:
    workQueue.put(word)
queueLock.release()

# 等待队列清空
while not workQueue.empty():
    pass

# 通知线程是时候退出
exitFlag = 1

# 等待所有线程完成
for t in threads:
    t.join()
print("退出主线程")
---执行结果--------------------------------------------------
开启线程:T1
开启线程:T2
开启线程:T3
T3 processing One
T1 processing Two
T2 processing Three
T3 processing Four
T2 processing Five
退出线程:T3
退出线程:T1
退出线程:T2
退出主线程

进程已结束,退出代码为 0

练习

在一个线程中,每秒循环输出当前的年月日时分秒;于此同时,在另一个线程中,实现张三的姓名每2秒打印输出4次结束。注意:都需要使用类和继承实现功能
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2022/1/17 14:26
# @Author  : 波澜不惊
# @File    : 题1.py
# 在一个线程中,每秒循环输出当前的年月日时分秒;于此同时,
# 在另一个线程中,实现张三的姓名每2秒打印输出4次结束。
# 注意:都需要使用类和继承实现功能

import threading
import time


class myThread1(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        num = 10
        while num > 0:              # 虽然题上没做要求,但还是不要一直循环的好
            print("%s" % (time.ctime(time.time())))
            time.sleep(1)
            num -= 1


class myThread2(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        num = 4
        while num > 0:
            time.sleep(2)
            print("张三")
            num -= 1


thread1 = myThread1()
thread1.start()
thread2 = myThread2()
thread2.start()
---执行结果------------------------------------------------------
Mon Jan 17 22:08:06 2022
Mon Jan 17 22:08:07 2022
张三
Mon Jan 17 22:08:08 2022
Mon Jan 17 22:08:09 2022
张三
Mon Jan 17 22:08:10 2022
Mon Jan 17 22:08:11 2022
张三
Mon Jan 17 22:08:12 2022
Mon Jan 17 22:08:13 2022
张三
Mon Jan 17 22:08:14 2022
Mon Jan 17 22:08:15 2022

进程已结束,退出代码为 0

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐