defrun(self): for i inrange(self.low,self.high): self.total+=i
thread1 = SummingThread(0,500000) thread2 = SummingThread(500000,1000000) thread1.start() # This actually causes the thread to run thread2.start() thread1.join() # This waits until the thread has completed thread2.join() # At this point, both threads have completed result = thread1.total + thread2.total print result
import threading from random import randint from time import sleep
defprint_number(number): # Sleeps a random 1 to 10 seconds rand_int_var = randint(1, 10) sleep(rand_int_var) print"Thread " + str(number) + " slept for " + str(rand_int_var) + " seconds"
thread_list = []
for i inrange(1, 10): # Instantiates the thread # (i) does not make a sequence, so (i,) t = threading.Thread(target=print_number, args=(i,)) # Sticks the thread in a list so that it remains accessible thread_list.append(t)
# Starts threads for thread in thread_list: thread.start()
# This blocks the calling thread until the thread whose join() method is called is terminated. # From http://docs.python.org/2/library/threading.html#thread-objects for thread in thread_list: thread.join()
# Demonstrates that the main process waited for threads to complete print"Done"