版权声明:== https://github.com/fyonecon == https://blog.csdn.net/weixin_41827162/article/details/84104621
-
1. 认识线程同步现象:
在https://blog.csdn.net/weixin_41827162/article/details/84104421线程异步中,
将方法1中:
建多个线程,同时执行多个线程,由新到旧逐个释放线程
改成:
创建一个线程,执行一个线程,释放一个线程
-
#!/usr/bin/python3
# 线程异步
import threading
import time
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, thread_id, name, counter):
threading.Thread.__init__(self)
self.thread_id = thread_id
self.name = name
self.counter = counter
pass
def run(self):
print("开始线程=" + self.name)
run_def(self.name, self.counter, 5)
print("退出线程=" + self.name)
pass
pass
def run_def(thread_name, delay, counter):
while counter:
if exitFlag:
thread_name.exit()
pass
time.sleep(delay)
# time.sleep(0)
list(thread_name)
counter -= 1
pass
pass
def list(thread_name):
print("\n执行线程=" + thread_name)
pass
threads = [] # 存储在线线程
# 创建线程
for this_t in range(1, 10):
t = myThread(this_t, "Thread-" + str(this_t), 0.1)
t.start()
t.join() # 线程同步,线程异步
threads.append(t)
pass
# 终止线程
# for t in threads:
# t.join()
# pass
print("程序完成!!")
-
2. 真正的线程同步:
#!/usr/bin/python3
# 线程同步
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("开启线程: " + self.name)
# 获取锁,用于线程同步
threadLock.acquire()
print_time(self.name, self.counter, 3)
# 释放锁,开启下一个线程
threadLock.release()
def print_time(threadName, delay, counter):
while counter:
time.sleep(0)
print("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
for cal in range(1, 100):
that = myThread(cal, "Thread-" + str(cal), cal).start()
print("创建了线程=" + str(cal))
threads.append(that)
pass
print("退出主线程")
-
扫描二维码关注公众号,回复:
4157580 查看本文章