Python

python多线程demo

这是一个python多线程demo脚本,供参考。

# -*- encoding: utf-8 -*-

# here put the import lib
import threading
import time

class WorkThread(threading.Thread):
    def run(self):
        while True:
            lock.acquire()  # 加线程锁
            endTime = int(round(time.time() * 1000))
            runTime = endTime - startTime
            if runTime <= 10000:  # 运行10s
                now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
                resultFile.write('#'*100+' '+now_time+' ' +
                                 str(self.getName())+' '+str(self.ident)+'\n')
            else:
                lock.release()  # 走到这里break需解锁
                break
            lock.release()  # 解线程锁

if __name__ == '__main__':
    lock = threading.Lock()
    startTime = int(round(time.time() * 1000))
    with open('result.txt', 'w', encoding='utf8') as resultFile:
        thread_list = list()
        # 创建2个工作线程
        for _ in range(2):
            t = WorkThread()
            thread_list.append(t)

        # 启动所有工作线程
        for t in thread_list:
            t.start()

        # 等待所有线程执行结束
        for t in thread_list:
            t.join()

    print('执行成功!')

留言

您的邮箱地址不会被公开。 必填项已用 * 标注