python中多线程指的是什么

  介绍

这篇文章主要介绍python中多线程指的是什么,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

<强> 1,多线程的理解

多进程和多线程都可以执行多个任务,线程是进程的一部分。线程的特点是线程之间可以共享内存和变量,资源消耗少(不过在Unix环境中,多进程和多线程资源调度消耗差距不明显,Unix调度较快),缺点是线程之间的同步和加锁比较麻烦。

<强> 2,python多线程创建

在python中,同样可以实现多线程,有两个标准模块线程和线程,不过我们主要使用更高级的线程模块。使用例子:

import 线程   import  time    def 目标():   ,,,print  & # 39;从而curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   ,,,time . sleep (1)   ,,,print  & # 39;从而curent  threading , % s  is 结束# 39;,%,threading.current_thread () .name    print  & # 39;从而,curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   目标==t  threading.Thread(目标),   t.start ()   t.join ()   print  & # 39;从而,curent  threading , % s  is 结束# 39;,%,threading.current_thread () . name

输出:

,curent  threading  MainThread  is 运行   从而curent  threading  Thread-1  is 运行   从而curent  threading  Thread-1  is 结束   从而curent  threading , MainThread  is 

结束开始是启动线程,加入是阻塞当前线程,即使得在当前线程结束时,不会退出。从结果可以看的到,主线程直到线程1结束之后才结束。

Python中,默认情况下,如果不加加入语句,那么主线程不会等到当前线程结束才结束,但却不会立即杀死该线程。如不加加入输出如下:

,curent  threading  MainThread  is 运行   从而curent  threading  Thread-1  is 运行   ,从而curent  threading  MainThread  is 结束   从而curent  threading , Thread-1  is 

结束但如果为线程实例添加t.setDaemon(真正的)之后,如果不加加入语句,那么当主线程结束之后,会杀死子线程。代码:

import 线程   import 时间   def 目标():   ,,,print  & # 39;从而curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   ,,,time . sleep (4)   ,,,print  & # 39;从而curent  threading , % s  is 结束# 39;,%,threading.current_thread () . name   print  & # 39;从而,curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   目标==t  threading.Thread(目标)   t.setDaemon(真正的)   t.start ()   t.join ()   print  & # 39;从而,curent  threading , % s  is 结束# 39;,%,threading.current_thread () . name

输出如下:

,curent  threading  MainThread  is 运行   从而curent  threading , Thread-1  is  runningthe  curent  threading , MainThread  is 结束

如果加上加入,并设置等待时间,就会等待线程一段时间再退出:

import 线程   import 时间   def 目标():   ,,,print  & # 39;从而curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   ,,,time . sleep (4)   ,,,print  & # 39;从而curent  threading , % s  is 结束# 39;,%,threading.current_thread () . name   print  & # 39;从而,curent  threading , % s  is 运行# 39;,%,threading.current_thread () . name   目标==t  threading.Thread(目标)   t.setDaemon(真正的)   t.start ()   t.join (1)

输出:

,curent  threading  MainThread  is 运行   从而curent  threading  Thread-1  is 运行   从而curent  threading , MainThread  is 

主结束线程等待1秒,就自动结束,并杀死子线程。如果加入不加等待时间,t.join(),就会一直等待,一直到子线程结束,输出如下:

,curent  threading  MainThread  is 运行   从而curent  threading  Thread-1  is 运行   从而curent  threading  Thread-1  is 结束   从而curent  threading , MainThread  is 结束

python中多线程指的是什么