美文网首页
python多线程

python多线程

作者: 裂开的汤圆 | 来源:发表于2019-06-04 23:48 被阅读0次

本文主要采用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()

执行过程:

多线程.png

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

python 线程详解--AstralWind

相关文章

  • GIL

    谈谈python的GIL、多线程、多进程 最近在看 Python 的多线程,经常我们会听到老手说:“python下...

  • Python多线程编程——多线程编程中的加锁机制

    如果大家对Python中的多线程编程不是很了解,推荐大家阅读之前的两篇文章:Python多线程编程——多线程基础介...

  • 5-线程(补充)

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python_提高

    GIL全局解释器锁 描述Python GIL的概念, 以及它对python多线程的影响?编写⼀个 多线程抓取⽹⻚的...

  • Python程序员都知道的入门知识の八

    目录【Python程序员都知道的入门知识】 1. 多线程threading、Queue Python的多线程由th...

  • Python多线程实现生产者消费者

    1. Python多线程介绍 Python提供了两个有关多线程的标准库,thread和threading。thre...

  • 多线程

    Python多线程原理与实战 目的: (1)了解python线程执行原理 (2)掌握多线程编程与线程同步 (3)了...

  • Python多线程(上)

    前言 说起Python的多线程,很多人都嗤之以鼻,说Python的多线程是假的多线程,没有用,或者说不好用,那本次...

  • Python 3中的多线程

    Python 3的多线程 Python 3的多线程模块threading在旧版_thread模块基础上进行了更高层...

  • Python 多线程抓取图片效率实验

    Python 多线程抓取图片效率实验 实验目的: 是学习python 多线程的工作原理,及通过抓取400张图片这种...

网友评论

      本文标题:python多线程

      本文链接:https://www.haomeiwen.com/subject/ejiltctx.html