代码如下:
import _thread
import time
# 为线程定义一个函数
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % (threadName, time.ctime(time.time())))
# 创建两个线程
try:
_thread.start_new_thread(print_time, ("Thread-1", 1,))
_thread.start_new_thread(print_time, ("Thread-2", 2,))
except:
print("Error: 无法启动线程")
while 1:
pass
网上找的代码,最后的while循环让我非常困惑,这是怎么做到运行的?
示例:
from threading import Thread,current_thread
import os
n = 100
def task(name):
global n
n = 22
print(f"子线程 : {name} {os.getpid()} {current_thread().name} {n}")
if __name__ == '__main__':
p = Thread(target=task,args=("派大星",))
p.start()
p.join()
print(f"主线程 : {os.getpid()} {current_thread().name} {n}")
'''输出
子线程 : 派大星 120 Thread-1 22
主线程 : 120 MainThread 22
'''
while循环.类似c语言的,while(1);
他可能是想写点什么东西,就先写个pass放在那里,省的ide报错,然后就忘了继续写就传网上了