Python多线程 -- 线程未启动

4

我对多线程模块比较陌生,但我的问题是线程似乎无法启动。我尝试使用currentThread函数来查看是否有新的线程启动,但我只能看到主线程。此外,在每个教程中,我都看到他们使用类或子类,如class t(threading.Thread)。那么我的方法是错误的还是我必须在Python 3中使用类来启动线程。

这是我写的一些脚本:

第一个:

    import threading

    def basicThread(threadName,nr):
        print("Thread name ",threadName,", alive threads ",nr)

    for i in range(0,11):
        print(threading.activeCount())
        print(threading.currentThread())
        t = threading.Thread(target = basicThread,args = ("Thread - %s" %i,i,))
        t.start()
        t.join()

第二点:

import threading

def openFile():
    try:
        file = open("haha.txt","r+")
        print("Finished in opening file : {0}".format(file))
    except IOError as e:
           print("Error : {0}".format(e))

def user(threadName,count):
    age = int(input("Enter your age : "))
    name = str(input("Enter your name : "))
    print(age,name)
    print(threadName,count)

threadList = []

thread_1 = threading.Thread(target = openFile)
thread_1.start()
thread_1.join()
thread_2 = threading.Thread(target = user,args = ("Thread - 2",threading.activeCount()))
thread_2.start()
thread_2.join()
2个回答

4
< p > thread.join() 的作用是等待线程完成它正在做的事情。为了让其他线程开始工作,将此行代码移动到过程的末尾。


3
在第一个示例中的for循环之外。 - Xavier Combelle

1
  1. current_thread() 返回主线程,因为你在主方法中调用它。从 "basicThread" 方法打印的行表示运行该方法的实际线程(即新形成的线程)。

  2. 将 thread_1.join() 移动到底部,与之前的答案相同。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接