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

yipeiwu_com7年前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> 

相关文章

numpy.linalg.eig() 计算矩阵特征向量方式

在PCA中有遇到,在这里记录一下 计算矩阵的特征值个特征向量,下面给出几个示例代码: 在使用前需要单独import一下 >>> from numpy import...

python: 判断tuple、list、dict是否为空的方法

Test tuple_test = () assert not tuple_test list_test = [] assert not list_test dict_test...

浅谈Python 的枚举 Enum

枚举是常用的功能,看看Python的枚举. from enum import Enum Month = Enum('Month', ('Jan', 'Feb', 'Mar', 'A...

python的即时标记项目练习笔记

python的即时标记项目练习笔记

这是《python基础教程》后面的实践,照着写写,一方面是来熟悉python的代码方式,另一方面是练习使用python中的基本的以及非基本的语法,做到熟能生巧。 这个项目一开始比较简单,...

判断python对象是否可调用的三种方式及其区别详解

查找资料,基本上判断python对象是否为可调用的函数,有三种方法 使用内置的callable函数 callable(func) 用于检查对象是否可调用,返回True也可能调用失败...