1.方法一:将要执行的函数作为参数传递给threading.Thread()
import threading import time def func(n): global count time.sleep(0.1) for i in range(n): count += 1 if __name__ == '__main__': count = 0 threads = [] for i in range(5): threads.append(threading.Thread(target=func, args=(1000,))) for t in threads: t.start() time.sleep(5) print('count:', count)
2.方法二:继承treading.Thread()类,并重写run()
import threading import time class myThread(threading.Thread): def __init__(self, n): threading.Thread.__init__(self) self.myThread_n = n def run(self): global count for i in range(self.myThread_n): count += 1 if __name__ == '__main__': cout = 0 threads = [] for i in range(5): threads.append(myThread(1000)) for t in threads: t.start() time.sleep(5) print('count:', count)