简体   繁体   中英

Python thread doesn't work as expected

well,I wrote a little snappet trying to know how to use python threading . But strangely the following code just quit quickly without the expected output. Is it because I shouldn't spawn threads by overiding the run() method?

import threading
from time import sleep
class mythread(threading.Thread):
    def __init__(self,target=None,thread_num=5):
        threading.Thread.__init__(self,target=None)
        self.thn = thread_num

    def run(self):
        for i in range(self.thn):
            t = threading.Thread(target=self.myfunc)
            t.start()
            t.join()
        myfunc(self.thn)

    def myfunc(num):
        print num,'\tI am doing sth.'
        sleep(0.5)
        print num,'\tI have done it.'

mythread()

You need to start the thread to make it actually do something:

t = mythread()
t.start()

If you bother to accept a target parameter in your constructor (why?), you shouldn't ignore this parameter. Maybe you want to pass it on to the Thread constructor. (Why?)

When you write mythread() , you instantiate the object. THe default constructor will be called, so __init__() will be executed.

You constructor doesn't have the any instruction of starting the thread.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM