You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python多线程程序调试求助:run()方法线程名称设置不达标

Python多线程程序名称设置问题修复

你的代码核心问题在于线程名称格式不符合需求,默认生成的Thread-1、Thread-2带横杠格式与要求的Thread1、Thread2不符,且未正确指定线程实例的名称,导致run()方法中获取的名称不符合预期。

以下是修正后的代码:

import threading

class MultithreadingDemo(threading.Thread):
    def __init__(self):
        super().__init__()
        self.__name = None
    
    def get_name(self):
        return self.__name

    def set_name(self, name):
        self.__name = name

    def run(self):
        curr_name = threading.current_thread().name
        self.set_name(curr_name)
        print(f"{self.get_name()} is running", end=" ")

class Multithread:
    @staticmethod
    def main():
        num = int(input("Enter the number of threads to spawn: "))
        threads = []

        for i in range(num):
            # 指定符合要求的线程名称格式
            thread_name = f"Thread{i+1}"
            t = MultithreadingDemo(name=thread_name)
            t.start()
            threads.append(t)

        for t in threads:
            t.join()
        print()

if __name__=="__main__":
    Multithread.main()

关键修改说明:

  • 自定义线程名称:创建线程实例时,通过name参数传入Thread{i+1}格式的名称,替代Thread类默认的带横杠命名规则,匹配需求中的输出格式。
  • 输出格式调整:修改print的end参数为空格,让多线程的输出可以连续显示在一行(符合你给出的示例效果),所有线程结束后添加换行保证排版整洁。
  • 严格遵循要求:run()方法中仍通过threading.current_thread().name获取名称,使用指定的set_name()和get_name()方法操作私有属性,完全符合题目中的注意事项要求。

内容的提问来源于stack exchange,提问作者Harsh Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 08:40:12