By import threading :
acc. to Python Docs:
Threads can be created by passing a callable object to the constructor, or by overriding the run() method in a subclass.
1) overriding the run() method in a subclass
import threading
import time
class myThreading(threading.Thread):
def __init__(self,counter):
print "In init__"
self.counter=counter
threading.Thread.__init__(self)
def run(self):
print "in Run " + self.name
tFunc(self.name,self.counter)
#time.sleep(1)
def pCount(self):
print threading.activeCount()
#print threading.enumerate()
def tFunc(name,counter):
while counter :
print "Name:" + name
counter -= 1
tObj1=myThreading(2)
tObj1.start()
start() starts the thread activity. It arranges for the object’s run() method to be invoked in a separate thread of control.
start() will create a thread. run() function will be executed in tht thread
tObj1.run() will not create thread. It will simply execute run method of same class.
Or in other words tObj1.run() will just call run() function in the current (calling) Thread.
2) passing a callable object to the constructor
import threading
import time
class myThreading(threading.Thread):
def __init__(self):
threading.Thread.__init__(self,target=tFunc,name='tName',args=(2,))
def tFunc(counter):
while counter:
print "Count :", counter
counter -= 1
tObj1=myThreading()
tObj1.start()
No comments:
Post a Comment