threading的join方法【join1】【java的join理解】【daemon = True】

yield():释放当前cpu的执行权
join():在线程a中调用 线程b的 b.join(),此时线程a就进入阻塞状态,直到线程b完全执行完以后,线程a才结束阻塞状态。


daemon = True
主进程退出了,还能继续运行

without join:
+---+---+------------------ main-thread
| |
| +........... child-thread(short)
+.................................. child-thread(long)

with join
+---+---+------------------***********+### main-thread
| | |
| +...........join() | child-thread(short)
+......................join()...... child-thread(long)

with join and daemon thread
+-+--+---+------------------***********+### parent-thread
| | | |
| | +...........join() | child-thread(short)
| +......................join()...... child-thread(long)
+,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, child-thread(long + daemonized)

'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could
continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
terminates when main-programs exits; is normally meant for
join-independent tasks


#没有join

# import threading
# #定义线程要调用的方法,*add可接收多个以非关键字方式传入的参数
# def action(*add):
#     # print(*add)
#     for arc in add:
#         #调用 getName() 方法获取当前执行该程序的线程名
#         print(threading.current_thread().getName() +" "+ arc)
# #定义为线程方法传入的参数
# my_tuple = ("http://c.biancheng.net/python/",\
#             "http://c.biancheng.net/shell/",\
#             "http://c.biancheng.net/java/")
# #创建线程
# thread = threading.Thread(target = action,args =my_tuple)
# #启动线程
# thread.start()
# #主线程执行如下语句
# for i in range(5):
#     print(threading.current_thread().getName())



#有join

import threading
#定义线程要调用的方法,*add可接收多个以非关键字方式传入的参数
def action(add):
    for arc in add:
        #调用 getName() 方法获取当前执行该程序的线程名
        print(threading.current_thread().getName() +" "+ arc)
#定义为线程方法传入的参数
my_tuple = ("http://c.biancheng.net/python/",\
            "http://c.biancheng.net/shell/",\
            "http://c.biancheng.net/java/")
#创建线程
thread = threading.Thread(target = action,args =my_tuple)
#启动线程
thread.start()
#指定 thread 线程优先执行完毕
thread.join()
#主线程执行如下语句
for i in range(5):
    print(threading.current_thread().getName())
posted @ 2021-01-11 14:06  该显示昵称已被使用了  阅读(125)  评论(0编辑  收藏  举报