多线程

一、创建

1.用threading模块创建多线程

①把一个函数传入并创建Thread实例,然后用start启动

import random,time,threading

def thread_run(urls):
print('Current %s is 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)
# MainThread is running
# Current Thread_1 is running
# Thread_1---->url_1
# Current Thread_2 is running
# Thread_2---->url_4
# Thread_2---->url_5
# Thread_2---->url_6
# Thread_2 ended.
# Thread_1---->url_2
# Thread_1---->url_3
# Thread_1 ended.
# MainThread ended.

②从threading.Thread继承并创建线程类,然后重写__init__() 和run()方法

import random, time, threading


class myThread(threading.Thread):
    def __init__(self, name, urls):
        super().__init__(name=name)
        self.urls = urls

    def run(self):
        print('Current %s is 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()
# MainThread is running
# Current Thread_1 is running
# Thread_1---->url_1
# Current Thread_2 is running
# Thread_2---->url_4
# Thread_2---->url_5
# Thread_2---->url_6
# Thread_1---->url_2
# Thread_2 ended.
# Thread_1---->url_3
# Thread_1 ended.
# MainThread ended.
2.使用threading.Thread
from threading import Thread

二、实例

def main(cand):
    pass

t1 = Thread(target=main, args=(cand_list_key[0],))
threads.append(t1)
t2 = Thread(target=main, args=(cand_list_key[1],))
threads.append(t2)
t3 = Thread(target=main, args=(cand_list_key[2],))
threads.append(t3)
t4 = Thread(target=main, args=(cand_list_key[3],))
threads.append(t4)
for t in threads:
    t.start()
for t in threads:  # 所有子线程结束了,再继续主线程
    t.join()
print('OK!')

多线程读写文件时,需要分块操作,每一块开一个线程。

ref:Python多线程循环

0

发表评论

邮箱地址不会被公开。 必填项已用*标注