Python 多线程运行,可是为什么是Thread-2先执行

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import thread
import time

def print_time(threadName, delay, count):
    print "%s: %s  %s \n" % (threadName, time.ctime(time.time()), str(count))
    count = count
    while count < 5:
        time.sleep(delay)
        count += 1
        print "%s: %s  %s" % (threadName, time.ctime(time.time()), str(count))
try:
    thread.start_new_thread(print_time, ("Thread-1", 1, 0))
    thread.start_new_thread(print_time, ("Thread-2", 3, 0))
except:
    print "Error: unable to start thread"
while 1:
    pass

运行结果:
图片描述

阅读 3.2k
4 个回答

随机的,但是python不推荐thread模块,建议用threading

这是随机的,只是你恰巧碰到 Thread 2 先打印

执行时机取决于操作系统调度,并不是先开始就先执行

随机的 而且就算先开始的线程也不一定会先打印

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题