Python实战:使用python实现多线程

他山之石,可以攻玉 ------《诗经·小雅·鹤鸣》

一、前言

如果大家对什么是线程、什么是进程仍存有疑惑的话,请Google查找,本文不再冗余介绍这些概念,本文旨在总结python实现多线程的几种方式。

Python3 线程中常用的两个模块为:

  • _thread
  • threading(推荐使用)

thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用"thread" 模块。为了兼容性,Python3 将 thread 重命名为 “_thread”。

下面用实际案例介绍三种实现多线程的方法。

二、Python实现多线程

1. 通过 _thread 实现多线程

Python中使用线程有两种方式:函数或者用类来包装线程对象。
函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程。语法如下:

_thread.start_new_thread ( function, args[, kwargs] )

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。

注:_thread对于进程何时退出没有任何控制。当主线程结束时,所有其他线程也都强制结束。不会发出警告或者进行适当的清理。因而python多线程一般使用较为高级的threading模块,它提供了完整的线程控制机制以及信号量机制。

案例:

# -*- coding: utf-8 -*-
import _thread
import time


def print_time(thread_name, sleep_time):
    for i in range(5):
        time.sleep(sleep_time)
        print("threadName: %s, time is %s" % (thread_name, time.ctime(time.time())))


if __name__ == "__main__":
    try:
        _thread.start_new_thread(print_time, ("thread-1", 2))
        _thread.start_new_thread(print_time, ("thread-2", 2))
    except:
        print("线程为启动")

while 1:
    pass

2. 通过threading.Thread进行创建多线程

python3.x中通过threading模块创建新的线程有两种方法:一种是通过threading.Thread(Target=executable Method)-即传递给Thread对象一个可执行方法(或对象);

# -*- coding: utf-8 -*-
import time
import threading


def print_time():
    for i in range(5):
        time.sleep(1)
        print("threadName: %s, time is %s" % (threading.current_thread().getName(),
                                              time.ctime(time.time())))


if __name__ == "__main__":
    t = threading.Thread(target=print_time)
    t2 = threading.Thread(target=print_time)
    t.start()
    t2.start()
    t.join() # join是阻塞当前线程(此处的当前线程时主线程) 主线程直到Thread-1结束之后才结束
    print("主线程打印内容")

3. 通过继承threading.Thread定义子类创建多线程

我们可以通过直接从 threading.Thread 继承创建一个新的子类,并实例化后调用 start() 方法启动新线程,即它调用了线程的 run() 方法:

# -*- coding: utf-8 -*-

import threading
import time

exitFlag = 0


class myThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter

    def run(self):
        print("开始线程:" + self.name)
        print_time(self.name, self.counter, 5)
        print("退出线程:" + self.name)


def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            threadName.exit()
        time.sleep(delay)
        print("%s: %s" % (threadName, time.ctime(time.time())))
        counter -= 1


if __name__ == "__main__":
    # 创建新线程
    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)

    # 开启新线程
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print("退出主线程")
发布了19 篇原创文章 · 获赞 67 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/m1090760001/article/details/103467195
今日推荐