2014-02-09 129 views
4

我对线程模块相当陌生,但我的问题是线程似乎无法启动。我尝试使用currentThread函数来查看它们是否是新线程的启动,但唯一的我看到的是主线程。另外,在每个教程中,我都看到它们使用类或子类,如类t(threading.Thread)。因此,它是我的方法是错误的或我使用类在Python 3 这里开始线程是一些脚本我写道:Python线程 - 线程无法启动

第一:

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

回答

4

thread.join()所做的是等待线程结束它正在做的事情。要允许其他线程启动,请将此行移至过程的末尾。

+3

...在最早出现的例子在for循环外 –

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

  2. 移动thread_1.join()的底部,与以前的答案