首页 > 解决方案 > .start() 不会导致启动线程

问题描述

我正在学习python中的多线程。我创建了以下示例,但 .start() 从未启动线程。请让我知道如何解决这个错误

代码

import threading
import time
import logging

class ThreadsSync:

def __new__(cls):
    """
    this will be invoked once the creation procedure of the object begins
    """
    instance = super(ThreadsSync,cls).__new__(cls)
    return instance

def __init__(self):
    """
    this will be invoked once the initialisation procedure of the object begins
    """
    self.configLogging()
    self.spawnThreads()

def configLogging(self):
    format = "%(asctime)s: %(message)s"
    logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
    logging.getLogger().setLevel("DEBUG")

def spawnThreads(self):
    if __name__ == "__main__":
        thread1 = threading.Thread(target=backgroundTask,args=(10,))
        #thread2 = threading.Thread(target=backgroundTask, args=(20,))
        thread1.start()
        #thread2.start()

def backgroundTask(threadName,numOfLoops):
    for i in numOfLoops:
        print(threadName, "-"*22, time.time())

标签: pythonpython-3.xpython-multithreading

解决方案


有几个问题

  1. 帖子中的缩进似乎不正确
  2. if __name__ == "__main__":好像发错地方了,删了
  3. 类从不被调用:在底部添加调用
  4. Thread输入更改为target=self.backgroundTask
  5. 改为numOfLoops_range(numOfLoops)
import threading
import time
import logging

class ThreadsSync:

    def __new__(cls):
        """
        this will be invoked once the creation procedure of the object begins
        """
        instance = super(ThreadsSync,cls).__new__(cls)
        return instance

    def __init__(self):
        """
        this will be invoked once the initialisation procedure of the object begins
        """
        self.configLogging()
        self.spawnThreads()

    def configLogging(self):
        format = "%(asctime)s: %(message)s"
        logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S")
        logging.getLogger().setLevel("DEBUG")

    def spawnThreads(self):
        thread1 = threading.Thread(target=self.backgroundTask,args=(10,))
        #thread2 = threading.Thread(target=backgroundTask, args=(20,))
        thread1.start()
        #thread2.start()

    def backgroundTask(threadName,numOfLoops):
        for i in range(numOfLoops):
            print(threadName, "-"*22, time.time())
if __name__==‘__main__’:
    ThreadsSync()

推荐阅读