Wednesday, April 20, 2011

How to create threads

The example show how to define the behavior of a thread and run it.
import threading
import time
import random

class MyThread(threading.Thread):
 def __init__(self, myName):
  self.myName = myName

 def run(self):
  while True:
   time.sleep(random.randint(0,3)) # wait a random time from 0 to 3 secs
   print "My name is",self.myName

thread1 = MyThread("1")
thread1.start() # the thread will run in background
thread2 = MyThread("2")
My name is 1
My name is 1
My name is 2
My name is 2
My name is 1
The two threads will print in the console their attribute myName with random time interval.

No comments:

Post a Comment