线程同步
//test.py
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
threadLock.acquire()
print_time(self.name, self.counter, 5)
threadLock.release()
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
#threading.Thread.exit()
return
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
threadLock = threading.Lock()
threads = []
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
thread1.start()
thread2.start()
#exitFlag = 1
threads.append(thread1)
threads.append(thread2)
for t in threads:
t.join()
print "Exiting Main Thread"
//result
# python test.py
Starting Thread-1
Starting Thread-2
Thread-2: Wed Nov 15 18:31:53 2017
Thread-2: Wed Nov 15 18:31:55 2017
Thread-2: Wed Nov 15 18:31:57 2017
Thread-2: Wed Nov 15 18:31:59 2017
Thread-2: Wed Nov 15 18:32:01 2017
Exiting Thread-2
Thread-1: Wed Nov 15 18:32:02 2017
Thread-1: Wed Nov 15 18:32:03 2017
Thread-1: Wed Nov 15 18:32:04 2017
Thread-1: Wed Nov 15 18:32:05 2017
Thread-1: Wed Nov 15 18:32:06 2017
Exiting Thread-1
Exiting Main Thread
Finally:
看到没有,关键任务是大家排排队,吃果果。
不要争,不要抢,谁先干的,就让他先干完,咋这么过瘾呢!!!:):)