本文共 1236 字,大约阅读时间需要 4 分钟。
在Python中并发编程时,线程的使用至关重要。线程可以分为内核线程和用户线程。内核线程由操作系统内核创建和管理,而用户线程则完全依赖于用户程序实现。线程的核心特性包括内存管理、抢占和睡眠(退让)等功能。
Python提供了两个主要的线程模块:_thread和threading。_thread适用于低级别操作,而threading模块功能更全面,适合大多数场景。
线程在Python中可以通过函数或类实现。函数方式使用_thread.start_new_thread,类方式则使用
。以下是两种方式的示例: import _threadimport time
定义线程函数:
def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % (threadName, time.ctime(time.time()))) 启动线程:
_thread.start_new_thread(print_time, ("Thread-1", 2))_thread.start_new_thread(print_time, ("Thread-2", 4)) threading模块提供了更高级别的线程管理功能,包括获取当前线程、枚举所有线程、获取活跃线程数等。同时,Thread类提供了多种方法来操作线程,如start()、join()、isAlive()等。
使用threading.Thread类创建线程更为简单。以下是一个使用继承的例子:
import threadingimport time
定义自定义线程类:
class MyThread(threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print("开始线程:" + self.name) print_time(self.name, self.counter, 5) print("退出线程:" + self.name) 创建并启动线程:
thread1 = MyThread(1, "Thread-1", 1)thread2 = MyThread(2, "Thread-2", 2)thread1.start()thread2.start() 等待线程结束:
thread1.join()thread2.join() 主线程退出:
print("退出主线程") 转载地址:http://xlhfk.baihongyu.com/