推荐一个不错的python教程
https://www.tutorialspoint.com/python/python_multithreading.htm
这里的多线程写的很nice, 例子很容易懂
我的例子如下:
multiThreadingRun继承threading.Thread的class只需要override __init__和run方法,使用时,实例化multiThreadingRun并传入threadName,方法func, 方法参数*args即可
import threading
import time
class multiThreadingRun(threading.Thread):
def __init__(self, threadName, func, *args):
threading.Thread.__init__(self)
self._func = func
self._args = args
self.threadName = threadName
def run(self):
print("Starting " + self.threadName)
self._func(*self._args)
print("Exiting " + self.threadName)
def print_time(threadName, counter, delay):
while counter:
time.sleep(delay)
print("%s: %s"%(threadName, time.ctime(time.time())))
counter -= 1
aa_list = ["thread1", "thread2", "thread3"]
my_threadings = []
for aa in aa_list:
my_threading = multiThreadingRun(aa, print_time, aa, 5, 1)
my_threading.start()
my_threadings.append(my_threading)
for my_threading in my_threadings:
my_threading.join()
输出:
Starting thread1
Starting thread2
Starting thread3
thread2: Tue Aug 21 13:00:49 2018
thread3: Tue Aug 21 13:00:49 2018
thread1: Tue Aug 21 13:00:49 2018
thread3: Tue Aug 21 13:00:50 2018
thread2: Tue Aug 21 13:00:50 2018
thread1: Tue Aug 21 13:00:50 2018
thread3: Tue Aug 21 13:00:51 2018
thread2: Tue Aug 21 13:00:51 2018
thread1: Tue Aug 21 13:00:51 2018
thread2: Tue Aug 21 13:00:52 2018
thread1: Tue Aug 21 13:00:52 2018
thread3: Tue Aug 21 13:00:52 2018
thread3: Tue Aug 21 13:00:53 2018
Exiting thread3
thread2: Tue Aug 21 13:00:53 2018
Exiting thread2
thread1: Tue Aug 21 13:00:53 2018
Exiting thread1
[Finished in 5.4s]