线程问题,没有输出就结束了
为什么我的代码没有任何输出就结束了?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", 2,))
_thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
print("Error: 无法启动线程")
import threading
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:
t1 = threading.Thread(target=print_time, args=("Thread-1", 2))
t2 = threading.Thread(target=print_time, args=("Thread-2", 4))
t1.start()
t2.start()
t1.join()
t2.join()
except:
print("Error: 无法启动线程")
_thread 模块对于进程退出并没有进行控制,所以只要主线程结束,子线程也随之结束
所以你这里子线程需要 sleep 进行等待,而主线程整个代码执行一瞬间就执行结束了,所以你看上去没有输出就结束了
你可以在主线程后面加上一个循环 或者 sleep ,这样就可以看到子线程的运行结果,参考代码:
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", 2,))
_thread.start_new_thread(print_time, ("Thread-2", 4,))
except:
print("Error: 无法启动线程")
time.sleep(10)
页:
[1]