分别运行以下每一部分代码,可以查看效果。
#! /usr/bin/env python
#coding=utf-8
import threading
import time
'''
#1、不加锁
num = 0
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1) #一定要sleep!!!
num = num + 1
msg = self.name + ' num is ---- ' + str(num)
print msg
def test():
for i in range(10):
s = MyThread() #实例化一个Thread对象,每个Thread对象代表着一个线程
s.start() #通过start()方法,开始线程活动
'''
#'''
class MyThread(threading.Thread):
def run(self):
for i in range(3):
time.sleep(1)
msg = self.name+' @ '+str(i)
print msg
def test():
for i in range(5):
t = MyThread()
t.start()
#'''
'''
#2、加锁
num = 0 #多个线程共享操作的数据
mu = threading.Lock() #创建一个锁
class MyThread(threading.Thread):
def run(self):
global num
time.sleep(1)
if mu.acquire(True): #获取锁状态,一个线程有锁时,别的线程只能在外面等着
num = num + 1
msg = self.name + ' num is ---- ' + str(num)
print msg
mu.release() #释放锁
def test():
for i in range(10):
s = MyThread()
s.start()
'''
if __name__ == '__main__':
test()