Python中的多线程

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

_thread

threading(推荐使用)

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

函数时调用:

最简单的读线程案例:

#threading模块创建线程实例

#步骤:1.用Thread类创建一个实例 2.实例化后调用start方法启动线程

from threading import Thread

#线程函数

def threadDemo(msg):

    print(msg)

if __name__ == '__main__':

    #实例化线程类,target参数为线程执行的函数,args参数为线程函数的参数

    thread1 = Thread(target=threadDemo,args=('this is a thread demo',))

    thread1.start()

输出:this is a thread demo

继承式调用

#步骤:1.继承Thread类创建一个新的子类 2.实例化后调用start方法启动线程

#线程函数

def threadDemo(msg):

    print(msg)

class MyThread(Thread):

    def __init__(self,msg):

        super(MyThread,self).__init__()

        self.msg = msg

    def run(self):

        threadDemo(self.msg)

if __name__ == '__main__':

    t1 = MyThread('thread t1')

    t2 = MyThread('thread t2')

    t1.start()

    t2.start()

    t1.join()

    t2.join()

输出:thread t1

           thread t2

线程同步

线程在运行时是相互独立的,线程与线程间互不影响

def print_time(threadName,count,delay):

    while count:

        time.sleep(delay)

        print("%s: %s" % (threadName, time.ctime(time.time())))

        count -= 1

class MyThread(Thread):

    def __init__(self,name,count):

        super(MyThread,self).__init__()

        self.name = name

        self.count = count

    def run(self):

        print('线程开始'+self.name)

        print_time(self.name,self.count,2)

        print('线程结束'+self.name)

if __name__ == '__main__':

    th1 = MyThread('th1',5)

    th2 = MyThread('th2',5)

    th1.start()

    th2.start()

    th1.join()

    th2.join()

    print('--主线程结束--')

输出结果:

线程开始th1

线程开始th2

th1: Tue Dec 31 10:25:30 2019

th2: Tue Dec 31 10:25:30 2019

th1: Tue Dec 31 10:25:32 2019

th2: Tue Dec 31 10:25:32 2019

th1: Tue Dec 31 10:25:34 2019

th2: Tue Dec 31 10:25:34 2019

th1: Tue Dec 31 10:25:36 2019

th2: Tue Dec 31 10:25:36 2019

th1: Tue Dec 31 10:25:38 2019

线程结束th1

th2: Tue Dec 31 10:25:38 2019

线程结束th2

--主线程结束--

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python有专门的线程模型.在Python中我们主要是通过thread和 threading这两个模块来实现的,...
    o小女巫o阅读 412评论 0 0
  • python中的多线程 基本操作 创建线程: 方式一:使用_thread模块直接开启一个线程 方式二:继承一个线程...
    AmaAnchor阅读 2,317评论 0 0
  • 1.耗时操作 一个线程默认有一个线程,这个线程叫主线程,默认情况下所有的任务(代码)都是在主线程中执行的 2.多线...
    发家致富靠养猪阅读 252评论 0 0
  • 如果可以,我愿在这场相遇的某一个时刻,在你美丽的一生中,向你借一天。只为了,只为了感受你真实的存在。 ...
    黑老二阅读 415评论 1 0
  • 才可以停下来看看手机,头疼的厉害,胳膊也酸疼得很,周末带孩子很累,何况孩子和我都病着。报的健身群突然都没时间打卡了...
    啾啾fing阅读 200评论 0 0