2

尝试学习多线程。我下载了一些示例代码来玩,我最终得到了这个:

import threading
import time

class myThread (threading.Thread):
    def __init__(self, threadID, name, delay, counter):
        super().__init__()
        self.threadID = threadID
        self.name = name
        self.delay = delay
        self.counter = counter
        threading.Thread.__init__(self)
        print(name,"created")
        print(self.name,"created")
    def run(self):
        print ("Starting " + self.name)
        print_time(self.name, self.delay, self.counter)
        print ("Exiting " + self.name)

def print_time(threadName, delay, counter):
    while counter:
        time.sleep(delay)
        print (threadName, time.ctime(time.time()))
        counter -= 1

# Create new threads
thread1 = myThread(1, "a", 1, 5)
thread2 = myThread(2, "b", 2, 3)

# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()

print ("Exiting Main Thread")

但至少可以说,我的输出是出乎意料的。

a created
Thread-2 created
b created
Thread-4 created
Starting Thread-2
Starting Thread-4
Thread-2 Mon Jan 14 16:14:29 2013
Thread-2 Mon Jan 14 16:14:30 2013
Thread-4 Mon Jan 14 16:14:30 2013
Thread-2 Mon Jan 14 16:14:31 2013
Thread-2 Mon Jan 14 16:14:32 2013
Thread-4 Mon Jan 14 16:14:32 2013
Thread-2 Mon Jan 14 16:14:33 2013
Exiting Thread-2
Thread-4 Mon Jan 14 16:14:34 2013
Exiting Thread-4
Exiting Main Thread

为什么 self.name 在以这种方式分配后不评估为“a”或“b”?

4

1 回答 1

4

name在 中重新初始化threading.Thread.__init__(self)。没有理由两次调用父构造函数。

于 2013-01-14T21:35:59.217 回答