问题:
问下,为什么这个程序执行到最后,打印了很多Thread-5,是线程5重复执行了?
如果我把sub中的time.sleep(1)注释的话,就是一个线程一个线程执行程序!
麻烦解答!
import threading, time
num = 5
lock = threading.Lock() # 创建同步锁
L = []
def sub():
global num
print('sub %s' % t.name)
lock.acquire() # 获得同步锁:不让别的线程在同一时刻运行
print(t.name)
temp = num
time.sleep(1)
num = temp - 1
lock.release() #解除同步锁
print('%s ' % t.name, num)
for i in range(5):
t = threading.Thread(target=sub)
t.start()
print('start %s' % t.name)
# L.append(t)
for T in L:
T.join()
print('s', num)
回答1:
for i in range(5):
t = threading.Thread(target=sub)
t.start()
print('start %s' % t.name)
for 循环循环了5次之后,t 就是线程5了呀.
def sub():
global num
print('sub %s' % t.name)
lock.acquire() # 获得同步锁:不让别的线程在同一时刻运行
print(t.name)
temp = num
time.sleep(1)
num = temp - 1
lock.release() #解除同步锁
print('%s ' % t.name, num)
这个里面的t 是全局的,for循环五次后,正好是线程5.然后你打印肯定是线程5 呀
下面是正确写法:
import threading, time
num = 5
lock = threading.Lock() # 创建同步锁
# L = []
def sub():
global num
print('sub %s' % t.name)
lock.acquire() # 获得同步锁:不让别的线程在同一时刻运行
print(threading.current_thread().getName())
temp = num
time.sleep(1)
num = temp - 1
lock.release() #解除同步锁
print('%s ' % t.name, num)
for i in range(5):
t = threading.Thread(target=sub)
t.start()
print('start %s' % t.name)
# L.append(t)
# for T in L:
# T.join()
print('s', num)
回答2:
for循环print语句确定在循环外面?