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