线程未在 python 脚本中并行运行

Utk*_*tel 2 python multithreading python-2.7

我是 python 和线程的新手。我试图一次运行多个线程。这是我的基本代码:

  import threading
  import time
  threads = []

  print "hello"

  class myThread(threading.Thread):
          def __init__(self,i):
                  threading.Thread.__init__(self)
                  print "i = ",i
                  for j in range(0,i):
                          print "j = ",j
                          time.sleep(5)

  for i in range(1,4):
          thread = myThread(i)
          thread.start()
Run Code Online (Sandbox Code Playgroud)

当 1 个线程正在等待时,time.sleep(5)我希望启动另一个线程。简而言之,所有线程都应该并行运行。

Sha*_*ane 6

您可能对如何创建子类有一些误解threading.Thread,首先__init__()方法大致代表Python中的构造函数,基本上每次创建实例时都会thread = myThread(i)执行它,因此在您的情况下执行时,它会阻塞到最后的__init__()

然后你应该将你的活动移到 中run(),这样当start()被调用时,线程将开始运行。例如:

import threading
import time
threads = []

print "hello"

class myThread(threading.Thread):
    def __init__(self, i):
        threading.Thread.__init__(self)
        self.i = i

    def run(self):
        print "i = ", self.i
        for j in range(0, self.i):
            print "j = ",j
            time.sleep(5)

for i in range(1,4):
    thread = myThread(i)
    thread.start()
Run Code Online (Sandbox Code Playgroud)

PS由于GILCPython 中存在 ,如果任务受 CPU 限制,您可能无法充分利用所有处理器的优势。