我们可以使用threading.Thread来创建线程。

举个例子

import time
import datetime
import threading


date_tinme_format = '%H:%M:%S'


def get_time_str():
    now = datetime.datetime.now()
    return now.strftime(date_tinme_format)


def thread_function(thread_id):
    print('Thread %d\t start at %s' % (thread_id, get_time_str()))
    print('Thread %d\t sleeping' % thread_id)
    time.sleep(4)
    print('Thread %d\t finish at %s' % (thread_id, get_time_str()))


def main():
    print('Main Thread start at %s' % get_time_str())
    threads = []
    for i in range(5):
        thread = threading.Thread(target=thread_function, args=(i, ))
        threads.append(thread)
    for i in range(5):
        threads[i].start()
        time.sleep(1)
    for i in range(5):
        threads[i].join()
    print('Main thread finish at %s' % get_time_str())



if __name__ == '__main__':
    main()

我们首先先创建线程,然后调用start方法来启动线程。最后,我们通过join方法来等待线程的结束,再退出主线程。使用threading.Thread对象可以自动帮我们管理线程锁。

当然,我们也可以通过创建一个继承自Thread的类,然后在里面实现run方法即可。

代码贴在下面

import time
import datetime
import threading


date_time_format = '%H:%M:%S'


def get_time_str():
    now = datetime.datetime.now()
    return now.strftime(date_time_format)


class MyThread(threading.Thread):
    def run(self):
        print('Thread %d\t start at %s' % (self.thread_id, get_time_str()))
        print('Thread %d\t sleeping' % self.thread_id)
        time.sleep(4)
        print('Thread %d\t finish at %s' % (self.thread_id, get_time_str()))

    def __init__(self, thread_id):
        super(MyThread, self).__init__()
        self.thread_id = thread_id






def main():
    print('Main Thread start at %s' % get_time_str())
    threads = []
    for i in range(5):
        thread = MyThread(i)
        threads.append(thread)
    for i in range(5):
        threads[i].start()
        time.sleep(1)
    for i in range(5):
        threads[i].join()
    print('Main thread finish at %s' % get_time_str())



if __name__ == '__main__':
    main()

线程同步

如果多个线程操作同一个对象,那么就需要线程同步。threading类提供了一个Lock对象,帮助我们实现线程同步。

上代码吧

import time
import threading


thread_lock = None


class MyThread(threading.Thread):
    def __init__(self, thread_id):
        super(MyThread, self).__init__()
        self.thread_id = thread_id

    def run(self):
        thread_lock.acquire()
        for i in range(3):
            print('Thread %d\t printing! times:%d' % (self.thread_id, i))
        thread_lock.release()
        time.sleep(1)
        thread_lock.acquire()
        for i in range(3):
            print('Thread %d\t printing! times:%d' % (self.thread_id, i))
        thread_lock.release()


def main():
    print('Main thread start.')
    threads = []
    for i in range(5):
        thread = MyThread(i)
        threads.append(thread)
    for i in range(5):
        threads[i].start()
    for i in range(5):
        threads[i].join()


if __name__ == '__main__':
    thread_lock = threading.Lock()
    main()

你也可能喜欢

发表评论