使用 join 在 python 中使用类和无类的多线程



我正在为我的项目在python多线程环境中练习。我已经开发(可能复制:))一个示例程序,该程序将使用线程连接方法,因此主线程将使用线程模型等到其他线程完成。

import threading
import time

class MyThread (threading.Thread):
    def __init__(self, thread_id, name, counter):
        threading.Thread.__init__(self)
        self.threadID = thread_id
        self.name = name
        self.counter = counter
    def run(self):
        print "Starting " + self.name
        threadLock.acquire()
        print_time(self.name, self.counter, 3)
        # Free lock to release next thread
        threadLock.release()

def print_time(thread_name, delay, counter):
    while counter:
        time.sleep(delay)
        print "%s: %s" % (thread_name, time.ctime(time.time()))
        counter -= 1
threadLock = threading.Lock()
thread1 = MyThread(1, "Thread-1", 1)
thread2 = MyThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
print 'waiting to finish the thread'
thread1.join()
thread2.join()
print "Exiting Main Thread"

以上输出:

Starting Thread-1
waiting to finish the threadStarting Thread-2
Thread-1: Tue Nov 18 16:31:04 2014
Thread-1: Tue Nov 18 16:31:05 2014
Thread-1: Tue Nov 18 16:31:06 2014
Thread-2: Tue Nov 18 16:31:08 2014
Thread-2: Tue Nov 18 16:31:10 2014
Thread-2: Tue Nov 18 16:31:12 2014
Exiting Main Thread
Process finished with exit code 0

当我评论这些连接方法行时

#thread1.join()
#thread2.join()

然后我得到的输出为

Starting Thread-1
waiting to finish the threadStarting Thread-2
Exiting Main Thread
Thread-1: Tue Nov 18 16:32:31 2014
Thread-1: Tue Nov 18 16:32:32 2014
Thread-1: Tue Nov 18 16:32:33 2014
Thread-2: Tue Nov 18 16:32:35 2014
Thread-2: Tue Nov 18 16:32:37 2014
Thread-2: Tue Nov 18 16:32:39 2014
Process finished with exit code 0

这是意料之中的

现在我又写了一段代码作为

import time
import threading

def printer():
    for _ in range(5):
        print 'Hello'
        time.sleep(1)
thread1 = threading.Thread(target=printer())
thread2 = threading.Thread(target=printer())
thread3 = threading.Thread(target=printer())
thread1.start()
thread2.start()
thread3.start()
print 'Bye Bye'

为此我没有使用join()线程方法,但我得到的输出为

Hello
Hello
:
Hello
:
Hello
:
Hello
Bye Bye
Process finished with exit code 0

通过使用join()我也得到了相同的输出。

根据我对线程和联接的理解,当我没有使用 join() 语句时,'Bye Bye'应该打印在中间的某个地方,而不是最后。

python中的类和简单函数是否有任何行为会发生变化?

target应该是一个函数,而不是函数的结果(除非该结果是一个函数)。 target=printer .请注意没有括号。

你有效地做了三次printer运行。然后启动了三个无关的线程。然后打印再见。

最新更新