解答
# coding=utf-8
import threading
import time
targetStr = 'abcdefg' # 不重复字符串
targetStrLength = len(targetStr)
resultStr = '' # 随机排序的字符串保存到这里
lock = threading.RLock()
class RandThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self):
time.sleep(0.5)
lock.acquire()
global targetStr
global resultStr
resultStr += targetStr[self.num]
lock.release()
def main():
threads = []
# 创建线程对象
for i in xrange(targetStrLength):
threads.append(RandThread(i))
# 启动线程
for t in threads:
t.start()
# 主线程等待子线程结束
for t in threads:
t.join()
print 'pre: ', targetStr
print 'random: ', resultStr
if __name__ == '__main__':
main()
帖子还没人回复快来抢沙发