繁体   English   中英

使用连接的python中具有类和不具有类的多线程

[英]Multi-threading with Class and without class in python using join

我正在为我的项目在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

当我评论这些join方法行时

#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 3次。 然后启动了三个无关的线程。 然后再见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM