python多线程

本文主要采用threading库

import threading

线程创建:

  • 方法一:传入参数实例化线程。
    • 函数:threading.Thread(target, args)
      • target:函数名
      • args:传入target函数的参数,用元组保存
# encoding:utf-8
# coding:utf-8
import threading


def 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 += 1

if __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-8
import threading


class 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 += 1

if __name__ == '__main__':
    thread1 = ThreadTest('thread1')
    thread2 = ThreadTest('thread2')
    thread1.start()
    thread2.start()

执行过程:

python多线程_第1张图片
多线程.png

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

python 线程详解--AstralWind

你可能感兴趣的:(python多线程)