python多线程

来源:互联网 发布:矢仓枫子 知乎 编辑:程序博客网 时间:2024/06/10 18:02

本文主要采用threading库

import threading

线程创建:

  • 方法一:传入参数实例化线程。
    • 函数:threading.Thread(target, args)
      • target:函数名
      • args:传入target函数的参数,用元组保存
# encoding:utf-8# coding:utf-8import threadingdef print_time(thread_name, delay):    print '线程{thread_name}启动'.format(thread_name=thread_name)    count = 0    while count < 5:        print 'count:%d' % count        # 将线程阻塞delay秒        # time.sleep(delay)        count += 1if __name__ == '__main__':    thread1 = threading.Thread(target=print_time,  args=('thread1', 1))    thread2 = threading.Thread(target=print_time, args=('thread2', 2))    thread1.start()    thread2.start()
  • 方法二:继承thread.Thread类,重写_init_()与_run_()方法
# coding:utf-8import threadingclass ThreadTest(threading.Thread):    def __init__(self, name):        threading.Thread.__init__(self)        self.name = name    def run(self):        print '线程{name}启动'.format(name=self.name)        count = 0        while count < 5:            print 'count:%d' % count            count += 1if __name__ == '__main__':    thread1 = ThreadTest('thread1')    thread2 = ThreadTest('thread2')    thread1.start()    thread2.start()

以下是运行截图

看到这里的时候,刚接触多线程的你(接触过的可以省略这段)会发现运行的结果和我的不一致,不用紧张,多线程执行的过程并不是线性的,结果是不可预测的。强推以下文章,理解线程的执行过程:python 线程详解–AstralWind

线程通信: