The difference between the start () and run () methods of the thread class in Python __python

Source: Internet
Author: User
Tags thread class

Both of these methods can start thread activity, but their differences are similar to the difference between start () and run () in the Java thread class.

First look at the Official document description:


Translation is:

Start () method

Start thread activity.

It can only be invoked once for each thread object, and it arranges the object to call the Run () method (not the current thread) in an additional separate thread.

When the method is invoked more than once in the same thread object, a RuntimeError (run-time error) is introduced.

Run () method

Represents a method of thread activity.

You can override this method in subclasses. The standard run () method calls the adjustable object that is passed to the object's constructor as the target parameter, and if so, the order and keyword parameters are obtained from args and Kargs respectively.

The following code was written to test:

#!/usr/bin/python
# coding=utf-8

Import Threading

Class Mythread (threading. Thread):
    def __init__ (self, ThreadID, name, counter):
        Threading. Thread.__init__ (self)
        self.threadid = ThreadID
        self.name = name
        Self.counter = Counter

    def run (self):
        currenttreadname = Threading.currentthread ()
        print "Running in", currenttreadname

thread = mythread (1, "Mythrd", 1)
Thread.run ()
Thread.Start ()

Mythread inherits from the thread class, I rewrite its constructor and run () method, the run () method obtains the current thread name by CurrentThread () and prints with the print function

The program then executes the run () and the Start () method separately

The output results are as follows:


You can see two methods in Mainthread and Mythread threads, respectively

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.