Python线程处理-线程未启动 [英] Python Threading -- Threads not starting

查看:392
本文介绍了Python线程处理-线程未启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对线程模块还很陌生,但我的问题是线程似乎无法启动.我试图使用currentThread函数来查看它们是新线程正在启​​动,但我唯一看到的是Main线程.另外,在每个教程中,我都看到它们使用类或子类,例如类t(threading.Thread).所以我的方法有问题吗,还是我必须使用类来启动python 3中的线程. 这是我写的一些脚本:

I'm quite new to the threading module, but my problem is that threads appear to not start.I tried to use the currentThread function to see is they are new threads starting but the only thing I see is the Main thread.Also, in every tutorial I see they use classes or subclasses, like class t(threading.Thread). So is it my method that's wrong or do I have to use classes to start threads in python 3. Here is some scripts I wrote:

第一个:

    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()

推荐答案

thread.join()的作用是等待线程结束其工作.要允许其他线程启动,请将此行移至过程的末尾.

What thread.join() does is it waits for the thread to end what it's doing. To allow other threads to start, move this line to the end of the procedure.

这篇关于Python线程处理-线程未启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆