Python reptile - process and thread 2

Multithreading

1, using the threading module creates a thread

One way: the incoming and create a Thread instance function, and then call the start method to begin
# coding=utf8
"""
创建多线程的方式一:
    把函数传入并创建Thread实例,然后调用start方法开始执行
"""
import random, time
import threading

def thread_run(urls):
    print 'Current thread %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

if __name__ == '__main__':
    print 'Current thread %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
Second way: inheritance Thread class and override the run method __init__
# coding=utf8
'''
创建多线程方式二:
    继承Thread类,重写__init__和run方法
'''
import threading
import time, random


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

    def run(self):
        print 'Current thread %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

if __name__ == '__main__':
    print 'Current thread %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

Guess you like

Origin www.cnblogs.com/lykxbg/p/11969374.html