# 不启用多线程,正常执行结果import threading
sum = 0
loopSum = 100000defmyAdd():global sum, loopSum
for i in range(1, loopSum):
sum += 1defmyMinu():global sum, loopSum
for i in range(1, loopSum):
sum -= 1if __name__ == '__main__':
myAdd()
print(sum)
myMinu()
print(sum)
99999
0
# 多线程执行两个方法import threading
sum = 0
loopSum = 100000defmyAdd():global sum, loopSum
for i in range(1, loopSum):
sum += 1defmyMinu():global sum, loopSum
for i in range(1, loopSum):
sum -= 1if __name__ == '__main__':
print("Stating ....{0}".format(sum))
# 启用多线程实例,查看执行结果
t1 = threading.Thread(target=myAdd, args=())
t2 = threading.Thread(target=myMinu, args=())
t1.start()
t2.start()
t1.join()
t2.join()
print("Done .... {0}".format(sum))
import threading
import time
import queue
# python2# from Queue import Queue# python3classProduer(threading.Thread):defrun(self):global queue
count = 0whileTrue:
if queue.qsize() < 1000:
for i in range(100):
count = count + 1
msg = "生成产品" + str(count)
queue.put(msg)
print(msg)
time.sleep(0.5)
classConsumer(threading.Thread):defrun(self):global queue
whileTrue:
if queue.qsize() > 100:
for i in range(3):
msg = self.name + "消费了" + queue.get()
print(msg)
time.sleep(1)
if __name__ == "__main__":
queue = queue.Queue()
for i in range(500):
queue.put("初始产品:"+str(i))
for i in range(2):
p = Produer()
p.start()
for i in range(5):
c = Consumer()
c.start()
import threading
import time
# 参数定义同一个资源最多几个线程同时使用
semphore = threading.Semaphore(3)
deffunc():if semphore.acquire():
for i in range(5):
print(threading.currentThread().getName() + "get semphore")
time.sleep(15)
semphore.release()
print(threading.currentThread().getName() + "release semphore")
for i in range(8):
t1 = threading.Thread(target=func)
t1.start()
threading.Timer
Timer : 是利用多线程在指定时间后启动一个功能
import threading
import time
deffunc():
print("I am body")
time.sleep(4)
print("bay")
if __name__ == "__main__":
t1 = threading.Timer(6, func)
t1.start()
i = 0while i < 6:
print("{0}..........".format(i))
time.sleep(2)
i += 1
0..........
1..........
2..........
I am body
3..........
4..........
bay
5..........
import threading
import time
lock = threading.RLock()
classMyThread(threading.Thread):defrun(self):global num
time.sleep(1)
if lock.acquire(1):
num += 1
msg = self.name + 'set num to ' + str(num)
print(msg)
lock.acquire()
lock.release()
lock.release()
num = 0defmytherad():for i in range(8):
t1 = MyThread()
t1.start()
if __name__ == '__main__':
mytherad()
Thread-77set num to 1
Thread-78set num to 2
Thread-79set num to 3
Thread-80set num to 4
Thread-81set num to 5
Thread-82set num to 6
Thread-83set num to 7
Thread-84set num to 8