Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python 线程

作者:农村混血兒   发布日期:2026-01-21   浏览:109

import threading

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

    def run(self):
        print(f"启动线程: {self.name}")
        # 获取锁,用于线程同步
        thread_lock.acquire()
        print_time(self.name, self.counter, 3)
        # 释放锁
        thread_lock.release()

def print_time(thread_name, delay, counter):
    while counter:
        print(f"{thread_name}: {time.ctime(time.time())}")
        time.sleep(delay)
        counter -= 1

thread_lock = 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("退出主线程")

解释说明:

  1. 导入模块threading 模块用于创建和管理线程。
  2. 定义线程类:继承 threading.Thread 类,重写 run 方法来定义线程执行的任务。
  3. 线程同步:使用 threading.Lock() 来确保多个线程不会同时访问共享资源。
  4. 创建和启动线程:通过实例化 MyThread 类并调用 start() 方法来启动线程。
  5. 等待线程结束:使用 join() 方法确保主线程等待所有子线程完成后再继续执行。

上一篇:randint在python中的用法

下一篇:python multiprocessing

大家都在看

python时间格式

pythoneval函数用法

python读取文件路径

staticmethod在python中有

python 保存json文件

python开发windows应用程序

python中len是什么意思

python 私有函数

python ord和chr

python中的yield

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站