#coding = utf-8
import _thread
import threading
from time import sleep, ctime
"""
threading, 基于线程的并发编程
threading.active_count(),返回当前活动的线程数。
threading.current_thread(),返回调用者空值线程。
threading.get_ident(), 返回当前线程的线程标识。
lock.acquire() 将锁状态从unlocked改为locked状态,或者阻塞当前线程。
Thread.join() 阻塞当前线程。
"""
loops = [5,1]
class ThreadFunc(object):
def __init__(self, func, args, name=''):
self.name = name
self.func = func
self.args = args
def __call__(self):
self.func(self.args[0], self.args[1]) #调用方法,2.3之前的用Apply方法。
def loop(nloop, nsec):
print("启动线程", nloop, "在 :", ctime())
print("当前线程状态资料, 名字:", threading.current_thread().name, ",ID :", threading.get_ident(), ",主线程 :", threading.main_thread().name)
sleep(nsec)
print("线程", nloop, "完成 :", ctime())
def main():
print("开始运行程序 :", ctime())
print("启动线程之前的线程数量:", threading.active_count())
threads = []
statuses = [] # 保持线程的状态
nloops = range(len(loops))
# 创建线程数组
for i in nloops:
t = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
threads.append(t)
statuses.append(False)
#开始运行线程
for i in nloops:
threads[i].start()
print("启动线程之后的线程数量 :", threading.active_count())
#等待所有线程
finished = False
while not finished:
finished = True
for i in nloops:
threads[i].join(0.01) ## 阻塞当前线程,直到线程运行结束或者超时。
if threads[i].is_alive():
finished = False # 任何线程是活动的,不结束。
else:
if statuses[i] == False:
print("线程", threads[i].name, "运行结束,剩余的线程数量:", threading.active_count())
print("活动线程的数量 :", threading.active_count())
statuses[i] = True
print("所有线程完成 :", ctime())
print("活动线程的数量 :", threading.active_count())
def threadLockObject(nloop, nsec, lock):
print("启动线程", nloop, "在 :", ctime())
print("当前线程状态资料, 名字:", threading.current_thread().name, ",ID :", threading.get_ident(), ",主线程 :", threading.main_thread().name)
for i in range(nsec):
print("........正在运行")
sleep(1)
print("线程", nloop, "完成 :", ctime())
lock.release()
def testthreadLockObject():
lock = _thread.allocate_lock()
lock.acquire() # from unlocked to locked状态
tid = _thread.start_new_thread(threadLockObject,(10, 5, lock))
print("主线程被阻塞。")
lock.acquire() #当前线程被阻塞。 等待线程运行完毕。
print("线程", tid, "运行完毕。")
# 从Thread继承
print("自定义线程对象")
class AsyncThread(threading.Thread):
def __init__(self, content):
threading.Thread.__init__(self)
self.content = content
def run(self):
for i in range(10):
print("..... 线程ID = %d 正在运行, 输出内容%s" %(threading.current_thread().ident, self.content))
sleep(1)
if __name__ == '__main__':
main()
print()
print("Lock的使用")
testthreadLockObject()
print("测试自定义线程类")
at = AsyncThread("这是我的自定义线程类")
at.start()
print("主线程继续运行。")
print("开始等待后台线程运行完毕")
at.join()
print("自定义后台线程运行完毕")
print("程序运行完毕。")