Python提供了两个模块用于实现多线程,thread和threading,thread是低级模块,threading是高级模块,对thread进行了封装,实现多线程有两种方式,分别是将一个函数传入Thread实例,然后调用start方法和继承threading.Thread类,重写_init_和run方法
1.将函数传入Thread实例方法
import random,time,threading
def thread_run(urls):
print("目前运行的线程是%s"%threading.current_thread().name)
for url in urls:
print("%s---->>>%s"%(threading.current_thread().name,url))
time.sleep(random.random())
print("%s ended..."%threading.current_thread().name)
if __name__ == "__main__":
print("目前运行的线程是%s"%threading.current_thread().name)
t1 = threading.Thread(target=thread_run,name="thread1",args=(["url_1","url_2","url_3"],))
t2 = threading.Thread(target=thread_run,name="thread2",args=(["url_4","url_5","url_6"],))
t1.start()
t2.start()
t1.join()
t2.join()
print("%s ended"%threading.current_thread().name)
- 运行结果
目前运行的线程是MainThread
目前运行的线程是thread1
thread1—->>>url_1
目前运行的线程是thread2
thread2—->>>url_4
thread1—->>>url_2
thread2—->>>url_5
thread1—->>>url_3
thread1 ended…
thread2—->>>url_6
thread2 ended…
MainThread ended
2.继承threading.Thread类
import random,threading,time
class MyThread(threading.Thread):
def __init__(self,name,urls):
threading.Thread.__init__(self,name=name)
self.urls = urls
def run(self):
print("目前运行的线程是%s"%threading.current_thread().name)
for url in self.urls:
print("%s---->>>%s"%(threading.current_thread().name,url,))
time.sleep(random.random())
print("%s ended"%threading.current_thread().name)
if __name__ == "__main__":
print("目前运行的线程是%s"%threading.current_thread().name)
t1 = MyThread(name="thread_1",urls=["url_1","url_2","url_3"])
t2 = MyThread(name="thread_2",urls=["url_4","url_5","url_6"])
t1.start()
t2.start()
t1.join()
t2.join()
print("%s ended"%threading.current_thread().name)
- 运行结果
目前运行的线程是MainThread
目前运行的线程是thread_1
thread_1—->>>url_1
目前运行的线程是thread_2
thread_2—->>>url_4
thread_2—->>>url_5
thread_1—->>>url_2
thread_2—->>>url_6
thread_1—->>>url_3
thread_2 ended
thread_1 ended
MainThread ended
3.线程的同步
python中提供了Lock和RLock对象实现线程同步,这两个对象的acquire和release类似与JAVA中的ReentrantLock的lock和unlock方法,用语获取和释放锁,对于Lock对象而言,一个线程只能只能acquire一次,而Rlock可以acquire多次,但每一个acquire必须对应有一个release