python多线程

假如想象 提交于 2021-02-13 12:02:35

python的标准库提供两个模块:thread和threading,thread是低级模块,threading是高级模块,对thread进行了封装

1 用threading模块创建多线程

  • 第一种方法是把一个函数传入并创建Thread实例,然后调用start方法执行;
#!coding:utf-8
import random
import time,threading

#新线程执行的代码
def thread_run(urls):
    print 'Current %s in running...' %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)

print('%s is running... ' %threading.current_thread().name)
t1 = threading.Thread(target=thread_run,name='Thread_1',args=(['url_1','url_2','url_3'],))
t2 = threading.Thread(target=thread_run,name='Thread_2',args=(['url_4','url_5','url_6'],))

t1.start()
t2.start()
t1.join()
t2.join()
print '%s ended.'% threading.current_thread().name

<br/> ``` C:\Python27\python.exe F:/python_scrapy/python_study/Thread_test.py MainThread is running... Current Thread_1 in running... Thread_1 --->>> url_1 Current Thread_2 in running... Thread_2 --->>> url_4 Thread_1 --->>> url_2 Thread_2 --->>> url_5 Thread_1 --->>> url_3 Thread_1 ended. Thread_2 --->>> url_6 Thread_2 ended. MainThread ended.

Process finished with exit code 0


* 直接从threading.Thread继承并创建线程类,然后重写__init__方法和run方法

#!coding:utf-8 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 'Current %s in running... '% 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

print '%s is running... '%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

* 运行结果:

C:\Python27\python.exe F:/python_scrapy/python_study/Threading.Thread_test.py MainThread is running... Current Thread_1 in running... Thread_1 ---->>> url_1 Current Thread_2 in running... Thread_2 ---->>> url_4 Thread_2 ---->>> url_5 Thread_1 ---->>> url_2 Thread_1 ---->>> url_3Thread_2 ---->>> url_6

Thread_2 ended. Thread_1 ended. MainThread ended.

Process finished with exit code 0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!