文件名:thread.py 環境:ubuntu linux & python2.6
import threading
import time
import os
class Test(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global count, mutex
thnm = threading.currentThread().getName()
while True:
mutex.acquire()
count = count + 1
print 'thread name=%s, count=%d'%(thnm, count)
mutex.release()
time.sleep(2)
if __name__ == '__main__':
global count, mutex
threads = []
num = 4
count = 0
mutex = threading.Lock()
for x in xrange(0, num):
threads.append(Test())
for t in threads:
t.start()
for t in threads:
t.join()
執行方式:python thread.py
執行結果:
thread name=Thread-1, count=1
thread name=Thread-2, count=2
thread name=Thread-3, count=3
thread name=Thread-4, count=4
thread name=Thread-1, count=5
thread name=Thread-2, count=6
thread name=Thread-3, count=7
thread name=Thread-4, count=8
......
轉載請註明出處:http://blog.csdn.net/liujian0616/article/details/7951226