#coding=utf-8import random
import string
import time
import threading
from threading import lock
class mythread(threading.thread):
def __init__(self, func,arg=()):
# super(mythread, self).__init__()
threading.thread.__init__(self)
self.func = func
self.arg=arg
self.lock=lock()
def run(self):
with self.lock:
self.result=self.func(*self.arg)
# self.result = self.func()
def get_result(self):
try:
return self.result
except exception:
return none
def get_generateid(x,y):
strings = ''.join(random.sample(string.hexdigits, random.randint(x,y)))
# strings=eggroll.generateuniqueid()
return strings
def main(data_totalsnumber):
st=time.time()
thread_list =
list_sampleids=
for i in range(data_totalsnumber):
t = mythread(get_generateid,arg=(16,18))
t.start()
for t in thread_list:
t.join()
# print(list_sampleids)
print(time.time()-st)
# real_idnumbers= len(set(list_sampleids))
# assert real_idnumbers == data_totalsnumber
if __name__ == '__main__':
main(data_totalsnumber=200000)
cost 85.71295762062073
threadpool 模式執行緒池呼叫
import timeimport threading
from concurrent.futures import threadpoolexecutor
class account(object):
"""銀行賬戶"""
def __init__(self):
self.balance = 0.0
self.lock = threading.lock()
def deposit(self, money):
# 通過鎖保護臨界資源
with self.lock:
new_balance = self.balance + money
time.sleep(0.001)
self.balance = new_balance
class addmoneythread(threading.thread):
"""自定義執行緒類"""
def __init__(self, account, money):
self.account = account
self.money = money
# 自定義執行緒的初始化方法中必須呼叫父類的初始化方法
super().__init__()
def run(self):
# 執行緒啟動之後要執行的操作
self.account.deposit(self.money)
def main():
"""主函式"""
account = account()
# 建立執行緒池
pool = threadpoolexecutor(max_workers=16)
futures =
st = time.time()
for _ in range(400):
# 建立執行緒的第1種方式
# threading.thread(
# target=account.deposit, args=(1, )
# ).start()
# 建立執行緒的第2種方式
# addmoneythread(account, 1).start()
# 建立執行緒的第3種方式
# 呼叫執行緒池中的執行緒來執行特定的任務
future = pool.submit(account.deposit, 1)
# 關閉執行緒池
pool.shutdown()
for future in futures:
future.result()
print("cost time",time.time()-st)
print(account.balance)
def main2():
pass
if __name__ == '__main__':
main()
關於java執行緒池
假設初始化乙個執行緒池,核心執行緒池數 corepoolsize 是5,最大執行緒數 maxpoolsize 是10 初始化的時候執行緒池裡是空的。阻塞佇列裡面也沒有任務 當來了乙個任務時,執行緒池中初始化乙個執行緒,再來乙個任務就在初始化乙個,當執行緒數量達到5個時,第6個任務就會放到阻塞佇列中,...
關於執行緒池ThreadPoolExecutor
threadpoolexecutor executor new threadpoolexecutor 3,8,3,timeunit.seconds,new linkedblockingqueue 這個執行緒池一共有5個引數 第乙個引數 執行緒池核心執行緒的個數 第二個引數 執行緒池中的最大執行緒數,...
執行緒池 關於執行緒池的五種狀態
在threadpoolexecutor類中定義了執行緒的五種狀態表示,通過atomicinteger 的高三位來表示執行緒的狀態 private static final int count bits integer.size 3 private static final int running 1...