Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

python - Inheritance threading.Thread class does not work

I'm new in multithreading, so the answer is probably very simple.

I'm trying to make two instances of one class and run them parallel. I've read that I can use class inheritance to do that.

class hello(threading.Thread):
    def __init__(self,min,max):
        threading.Thread.__init__(self)
        time.sleep(max)

        for i in range(1000):
            print random.choice(range(min,max))

h = hello(3,5)
k = hello(0,3)

I've noticed that this does not work (the first outputs are numbers between 3 and 5)

Could you explain what am I doing wrong?
Is this inheritance dedicated to do something else?

EDIT: I want to run these two objects parallel so since the second object has smaller wait, it has to print those numbers sooner.

According to porglezomps comment, I've tried to change the code - add a method which prints those numbers but it prints it sequentially. The problem is still there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The documentation for threading says that you should override the run() method, and then use the start() method to begin execution on a new thread. In your case, your code should be:

class Hello(threading.Thread):
    def __init__(self, min, max):
        self.min, self.max = min, max
        threading.Thread.__init__(self)

    def run(self):
        time.sleep(self.max)

        for i in range(1000):
            print random.choice(range(self.min, self.max))

# This creates the thread objects, but they don't do anything yet
h = Hello(3,5)
k = Hello(0,3)

# This causes each thread to do its work
h.start()
k.start()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...