Regular无限多线程
import threading
import numpy as np
import time
class BuildThread(threading.Thread):
def __init__(self, name, alist):
threading.Thread.__init__(self)
self.alist = alist
def run(self):
self.alist.append(np.random.random_integers(1,10))
time.sleep(1)
thread_num = 4 # 想要多少写多少
g_collect = []
threads = []
start_time = time.time()
for thread in range(thread_num):
# 不使用多线程
# g_collect.append(np.random.random_integers(1,10))
# time.sleep(1)
# 使用多线程
_thread = BuildThread('Thread-1', g_collect)
threads.append(_thread)
_thread.start()
for thread in threads: # 保护:必须所有threads里的线程结束才可以进入下一步
thread.join()
end_time = time.time()
run_time = end_time - start_time
print(g_collect)
print('run time: ', run_time)
同时最多有 4 个线程
import threading
import numpy as np
import time
class BuildThread(threading.Thread):
def __init__(self, name, alist, threads):
threading.Thread.__init__(self)
self.alist = alist
self.threads = threads
def run(self):
self.alist.append(np.random.random_integers(1,10))
time.sleep(1)
self.threads.remove(self)
thread_num = 10
g_collect = []
threads = []
start_time = time.time()
for thread in range(thread_num):
while len(threads) >= 4: # 同时最多有4个线程
pass
_thread = BuildThread('Thread-{}'.format(threads), g_collect, threads)
threads.append(_thread)
_thread.start()
print(threads)
end_time = time.time()
run_time = end_time - start_time
print(g_collect)
print('run time: ', run_time)