Python multithreaded Programming Simple example

Source: Internet
Author: User
Tags datetime

I like to use code to understand the program, not the tutorial alone.
Class ThreadClass inherits from Threading. Thread, and because of that, you need to define a run method that executes the code that you want to run in that thread. The only thing to note in this run method is that Self.getname () is a method for determining the name of the thread.

The code is as follows Copy Code

#!/usr/bin/env python
#coding =utf-8
Import Threading
Import datetime
Import time
Import random
&NBSP
Class ThreadClass (threading). Thread):
    def run (self):
        now = Datetime.datetime.now ()
        print "%s says Hello World at time:%s"% (self.ge Tname (), now)
        x = random.randint (1,5)
         print x
        time.sleep (x)
         print ' End%s '% (Self.getname ())
 
 
to I in range (5):
  &N Bsp t = ThreadClass ()
    t.start ()
Output

Thread-1 says Hello World in time:2014-07-11 16:22:56.820320thread-2 says Hello World at time:2014-07-11 16:22:56.820502

5
Thread-3 says Hello World at time:2014-07-11 16:22:56.820777
4
4
Thread-4 says Hello World at time:2014-07-11 16:22:56.820988
5
Thread-5 says Hello World at time:2014-07-11 16:22:56.821276

4
End Thread-1
End Thread-3
End Thread-5
End Thread-2
End Thread-4

We can see that 5 threads of threading are running in parallel, not sequentially.

Points:
1. Define a multithreaded class

The code is as follows Copy Code
Class ThreadClass (threading. Thread):

2. Must be run with function

The code is as follows Copy Code

def run (self):

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.