Threading Básico
- exemplo: join.py:
1 #!/usr/bin/python 2 import threading 3 import time 4 5 class ThreadOne(threading.Thread): 6 7 def run(self): 8 9 print 'Thread', self.getName(), 'started.' 10 time.sleep(5) 11 print 'Thread', self.getName(), 'ended.' 12 13 class ThreadTwo(threading.Thread): 14 15 def run (self): 16 17 print 'Thread', self.getName(), 'started.' 18 thingOne.join() 19 print 'Thread', self.getName(), 'ended.' 20 21 thingOne = ThreadOne() 22 thingOne.start() 23 thingTwo = ThreadTwo() 24 thingTwo.start()
- exemplo: live.py:
1 #!/usr/bin/python 2 import threading 3 import time 4 5 class TestThread(threading.Thread): 6 def run (self): 7 print 'Patient: Doctor, am I going to die?' 8 9 class AnotherThread(TestThread): 10 def run(self): 11 TestThread.run(self) 12 time.sleep (10) 13 14 dying = TestThread() 15 dying.start() 16 17 if dying.isAlive(): 18 print 'Doctor: No.' 19 else: 20 print 'Doctor: Next!' 21 22 living = AnotherThread() 23 living.start() 24 25 if living.isAlive(): 26 print 'Doctor: No.' 27 else: 28 print 'Doctor: Next!'
- exemplo: lowlevel.py:
- exemplo: named.py:
1 #!/usr/bin/python 2 import threading 3 4 class TestThread(threading.Thread): 5 6 def run(self): 7 print 'Hello, my name is', self.getName() 8 9 cazaril = TestThread() 10 cazaril.setName('Cazaril') 11 cazaril.start() 12 13 ista = TestThread() 14 ista.setName('Ista') 15 ista.start() 16 17 TestThread().start()