import threading
import time
def one_thread(name,id):
print("start....")
print(name)
print(id)
time.sleep(5)
print("end...")
print("start thread")
threading.Thread(target=one_thread, args=(), kwargs={"name": 111, "id": 222}).start()
# args是一个list
# kwargs是一个字典,需要对应函数的key
print("end thread")
start thread
start....
111
222
end thread
end...
import threading
import time
class myThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
def run(self):
print_time(self.threadID, self.name)
num = 0
def print_time(threadID, name):
global num
# 每一个线程循环10次,最终总循环次数为30次
for i in range(10):
print("start run")
time.sleep(2)
print(i)
num += 1
print("thread_id=%s:name=%s" % (threadID, name))
if __name__ == '__main__':
threads = []
# 新增三个线程
for i in range(3):
name = "Thread-%d" % i
t = myThread(i, name)
t.start()
threads.append(t)
for t in threads:
t.join()
print("所有线程执行完毕")
print("总循环次数为:%s" % num)
start run
start run
start run
0
0
...
thread_id=1:name=Thread-1
所有线程执行完毕
总循环次数为:30
global
如果大家对于学习Python有任何问题,学习方法,学习路线,如何学习有效率的问题,可以随时来咨询我,或者缺少系统学习资料的,我做这行年头比较久,自认为还是比较有经验的,可以帮助大家提出建设性建议,这是我的Python交流qun:785128166,有任何问题可以随时来咨询我。
# -*- coding: utf-8 -*-
import time
import threading
# 创建锁对象
lock = threading.Lock()
num = 0
def run(n):
global num
for i in range(10):
# 加锁 为了确保下面代码只能由一个线程从头到尾的执行
# 会阻止多线程的并发执行,所以效率会大大降低
"""
lock.acquire()
try:
num = num - n
num = num + n
finally:
# 解锁
lock.release()
"""
with lock:
time.sleep(2)
print("start")
num = num + 1
print("==============")
if __name__ == '__main__':
t1 = threading.Thread(target=run,args=(6,))
t2 = threading.Thread(target=run,args=(9,))
t1.start()
t2.start()
t1.join()
t2.join()
print("num = %s"%(num))
start
==============
...
num = 20
import threading
import time
import queue
q = queue.Queue(10)
threadLock = threading.Lock()
class myThread(threading.Thread):
def __init__(self, threadID, name):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.exitFlag = 0
def run(self):
while not self.exitFlag:
threadLock.acquire()
if not q.empty():
id = q.get()
print_time(self.name, id)
threadLock.release()
else:
threadLock.release()
def print_time(threadName, id):
print ("%s:%s:%s"%(threadName,time.ctime(time.time()),id))
# pass
# 创建3个线程
threads = []
for i in range(3):
name = "Thread-%d" % i
t = myThread(i, name)
t.start()
threads.append(t)
print(threads)
# 新增队列数据
for i in range(10000):
q_name = "Queue:%d" % i
q.put(q_name)
# 等待队列清空
while not q.empty():
pass
# 也可以join方法,与上同效
# q.join()
# 通知线程,处理完之后关闭
for t in threads:
t.exitFlag = 1
# 等待所有线程结束之后才退出
for t in threads:
t.join()
print("Exiting Main Thread")
q.empty()
前加上线程锁,因为可能会出现这样的一种情况。q.get(timeout=10)
超时操作来弥补这一问题。[, , ]
Thread-1:Sat Aug 22 11:36:29 2020:Queue:0
Thread-1:Sat Aug 22 11:36:29 2020:Queue:1
...
Thread-1:Sat Aug 22 11:36:30 2020:Queue:9998
Thread-1:Sat Aug 22 11:36:30 2020:Queue:9999
Exiting Main Thread
map
的使用,接受一个List的数据,会循环调用from concurrent.futures.thread import ThreadPoolExecutor
import time
num = 0
def print_time(data):
global num
num += 1
time.sleep(2)
print("start_%s" % data)
print("============")
data = []
for i in range(50):
data.append(i)
with ThreadPoolExecutor(10) as pool:
result = pool.map(print_time, data)
# 等待所有线程执行完毕
for i in result:
pass
print("循环次数=%s" % num)
============
start_46
start_49
============
============
循环次数=50
submit
接受list的数据,也可以接受字典rom concurrent.futures.thread import ThreadPoolExecutor
from concurrent.futures import as_completed
import time
def print_time(data):
time.sleep(2)
print("start_%s" % data)
print("============")
data = []
for i in range(50):
data.append(i)
with ThreadPoolExecutor(10) as executor:
future_list = []
for i in range(10):
# future = executor.submit(print_time,data)
future = executor.submit(print_time, {"name": 111, "id": 222})
future_list.append(future)
for res in as_completed(future_list): # 这个futrure_list是你future对象的列表
print(res.result())