Python线程中对join方法的运用的教程

yipeiwu_com6年前Python基础

join 方法:阻塞线程 , 直到该线程执行完毕

因此  ,可以对join加一个超时操作 , join([timeout]),超过设置时间,就不再阻塞线程

jion加上还有一个后果就是, 子线程和主线程绑定在一起 , 直到子线程运行完毕,才开始执行子线程。


代码 有join:

在CODE上查看代码片派生到我的代码片

  #-*- coding: UTF-8 -*-  
   
   
  import threading 
  from time import sleep 
   
  def fun(): 

在CODE上查看代码片派生到我的代码片

  <span style="white-space:pre">  </span>i= 5 
    while i > 0: 
      print(111111) 
      sleep(10) 

在CODE上查看代码片派生到我的代码片

  <span style="white-space:pre">    </span>i-- 
   
  if __name__ == '__main__': 
   
   
    a = threading.Thread(target = fun) 
    a.start() 
    a.join() 
    while True: 
      print('aaaaaaa') 
      sleep(1) 

在CODE上查看代码片派生到我的代码片

    输出:<pre name="code" class="python">111111 输完之后, 才输出 <span style="font-family: Arial, Helvetica, sans-serif;">aaaaaaa </span> 

在CODE上查看代码片派生到我的代码片

     

代码: 无join

在CODE上查看代码片派生到我的代码片

  #-*- coding: UTF-8 -*-  
   
   
  import threading 
  from time import sleep 
   
  def fun(): 
    while True: 
      print(111111) 
      sleep(10) 
   
  if __name__ == '__main__': 
   
   
    a = threading.Thread(target = fun) 
    a.start() 
    while True: 
      print('aaaaaaa') 
      sleep(1) 

在CODE上查看代码片派生到我的代码片

    <pre name="code" class="python" style="font-size:18px;">111111 和 <span style="font-family: Arial, Helvetica, sans-serif;">aaaaaaa  间隔输出</span> 

相关文章

Python 比较两个数组的元素的异同方法

通过set()获取两个数组的交/并/差集: print set(a).intersection(set(b)) # 交集 print set(a).union(set(b)) # 并...

详解Python中映射类型的内建函数和工厂函数

1.基本函数介绍 (1)标准类型函数[type()、str()和 cmp()]         对一个字典调用typ...

解决Python requests 报错方法集锦

python版本和ssl版本都会导致 requests在请求https网站时候会出一些错误,最好使用新版本。 1 Python2.6x use requests 一台老Centos机器上...

使用python提取html文件中的特定数据的实现代码

例如 具有如下结构的html文件 复制代码 代码如下: <div class='entry-content'> <p>感兴趣内容1</p> <p...

cProfile Python性能分析工具使用详解

cProfile Python性能分析工具使用详解

前言 Python自带了几个性能分析的模块:profile、cProfile和hotshot,使用方法基本都差不多,无非模块是纯Python还是用C写的。本文介绍cProfile。 例子...