先偿试一下比较低级一些的Thread
下篇再偿试封装更好的Threading
Coding:
__anthor__='jave.lin'
import thread
import Queue
import time
import random
def test(locker, threadName, r, q):
print("at %f, %s getting the lock\m" % (time.time(), threadName))
locker.acquire() #blocking the thread if the locker.locked() in this thread or anthor thread
sleepSeconds = r.randint(1, 5)
print("at %f, %s got the lock, and sleep %d seconds\n" % (time.time(), threadName, sleepSeconds))
time.sleep(sleepSeconds)
print("at %f, %s release the lock\n" % (time.time(), threadName))
locker.release()
print("thread%d, exit\n" % q.get())
q.task_done() #tell the queue one task done, until all the task done, Queue.join will unblocking
def main():
r = random.Random()
l = thread.allocate_lock()
q = Queue.Queue()
for i in xrange(5):
q.put(i)
thread.start_new_thread(test, (l, "thread%d" % i, r, q))
print("waitting for all the thread action complete!\n")
q.join()
print("all thread action complete, "),
print("exitting the testThread.py")
if __name__=='__main__':
main()