Python语法学习之线程的创建与常用方法详解

  

Python语法学习之线程的创建与常用方法详解

前言

Python是一种非常流行的编程语言之一,它具有简洁明了的语法、高效的性能和广泛的应用场景。本文将介绍Python语法学习的一个重要方面——线程的创建与常用方法。

线程的基本概念

在计算机科学中,线程是一种执行体(执行路径),也被称为轻量级进程。线程仅包含程序计数器、寄存器和栈,这使得它们的创建和销毁开销非常小。线程在同一进程中共享内存空间,因此它们之间的通信非常高效。

线程的创建方式

Python 有两个模块支持线程的使用:_thread 和 threading。

_thread 模块

使用 _thread 模块中的 start_new_thread() 函数来创建新线程。这个函数需要传入两个参数: 一个是函数名,另一个是可选参数,可选参数是以tuple的形式传入。

示例:

import _thread
import time

# 定义一个函数,该函数作为线程的主体
def print_time(threadName, delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print("{}: {}".format(threadName, time.ctime(time.time())))

# 创建新线程
try:
    _thread.start_new_thread(print_time, ("Thread 1", 1))
    _thread.start_new_thread(print_time, ("Thread 2", 2))
except:
    print("Error: 无法启动线程")

# 主线程继续执行
while 1:
    pass

threading 模块

Python中使用更广泛的线程模块是 threading 模块。通过定义线程类来创建线程。

示例:

import threading
import time

# 定义一个线程类
class MyThread(threading.Thread):
    def __init__(self, thread_name, delay):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.delay = delay

    # 重写 threading.Thread 类中的 run() 函数,该函数作为线程的主体
    def run(self):
        print("开始线程:" + self.thread_name)
        count = 0
        while count < 5:
            time.sleep(self.delay)
            count += 1
            print("{}: {}".format(self.thread_name, time.ctime(time.time())))
        print("结束线程:" + self.thread_name)

# 创建新线程
try:
    thread1 = MyThread("Thread 1", 1)
    thread1.start()
    thread2 = MyThread("Thread 2", 2)
    thread2.start()
except:
    print("Error: 无法启动线程")

# 主线程继续执行
while 1:
    pass

常用的线程方法

线程类中包含了多个常用的方法,这里对常用的方法进行简单介绍。

run()

run() 方法是线程的主体函数,它定义了线程的实际工作内容。在线程启动时被调用。

示例:

import threading

# 定义一个线程类
class MyThread(threading.Thread):
    def __init__(self, thread_name):
        threading.Thread.__init__(self)
        self.thread_name = thread_name

    # 重写 threading.Thread 类中的 run() 函数,该函数作为线程的主体
    def run(self):
        print("开始线程:" + self.thread_name)

# 创建新线程
try:
    thread = MyThread("Thread 1")
    thread.start()
except:
    print("Error: 无法启动线程")

start()

start() 方法是启动线程的方法,在线程对象的 start() 方法被调用时,该线程就会开始执行。程序使用 start() 方法后并不会立即执行 run() 方法,而是通过 CPU 调度来进行优先级排序,当优先级最高的线程准备执行时,CPU 调用其 run() 方法开始执行线程。

示例:

import threading

# 定义一个线程类
class MyThread(threading.Thread):
    def __init__(self, thread_name):
        threading.Thread.__init__(self)
        self.thread_name = thread_name

    # 重写 threading.Thread 类中的 run() 函数,该函数作为线程的主体
    def run(self):
        print("开始线程:" + self.thread_name)

# 创建新线程
try:
    thread = MyThread("Thread 1")
    thread.start()
except:
    print("Error: 无法启动线程")

join()

join() 方法使得调用线程阻塞,直到被调用 join() 方法的线程运行结束。这通常是为了等待另一个线程完成后再继续执行。

示例:

import threading
import time

# 定义一个线程类
class MyThread(threading.Thread):
    def __init__(self, thread_name, delay):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.delay = delay

    # 重写 threading.Thread 类中的 run() 函数,该函数作为线程的主体
    def run(self):
        print("开始线程:" + self.thread_name)
        count = 0
        while count < 5:
            time.sleep(self.delay)
            count += 1
            print("{}: {}".format(self.thread_name, time.ctime(time.time())))
        print("结束线程:" + self.thread_name)

# 创建新线程
try:
    thread1 = MyThread("Thread 1", 1)
    thread1.start()
    thread2 = MyThread("Thread 2", 2)
    thread2.start()
    # 等待线程1结束
    thread1.join()
    # 等待线程2结束
    thread2.join()
except:
    print("Error: 无法启动线程")

is_alive()

is_alive() 方法用于判断线程是否处于活动状态。如果线程是活动状态返回 True,否则返回 False。

示例:

import threading
import time

# 定义一个线程类
class MyThread(threading.Thread):
    def __init__(self, thread_name, delay):
        threading.Thread.__init__(self)
        self.thread_name = thread_name
        self.delay = delay

    # 重写 threading.Thread 类中的 run() 函数,该函数作为线程的主体
    def run(self):
        print("开始线程:" + self.thread_name)
        count = 0
        while count < 5:
            time.sleep(self.delay)
            count += 1
            print("{}: {}".format(self.thread_name, time.ctime(time.time())))
        print("结束线程:" + self.thread_name)

# 创建新线程
try:
    thread1 = MyThread("Thread 1", 1)
    print("线程1是否活跃:{}".format(thread1.is_alive()))
    thread1.start()
    print("线程1是否活跃:{}".format(thread1.is_alive()))
except:
    print("Error: 无法启动线程")

结语

通过本文,可以了解到Python语法中关于线程的创建与常用方法,帮助大家更好地学习和使用Python。

相关文章