初学Python:多线程脚本-重新写一个类,继承threading.Thread(第二种)

第二种写法(简略):重新写一个类,继承threading.Thread

先看一个简单的例子理解一下:

注意一点:**派生类中重写了父类threading.Thread的run()方法,其他方法(除了构造函数)都不应在子类中被重写,换句话说,在子类中只有_init_()和run()方法被重写。**使用线程的时候先生成一个子线程类的对象,然后对象调用start()方法就可以运行线程啦(start调用run)
这儿“派生类”没去查阅,我不了解

Sample1

# /usr/bin/python
# -*- coding:utf-8 -*-

import threading

class Sample_zb(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global lock
        global i
        lock.acquire()
        i += 1
        print (i)
        lock.release()

lock = threading.Lock()
i = 0

def main():
    ###########
    #不能把i和lock写在这儿,涉及变量作用域问题
    #i = 0
    #lock = threading.Lock()
    ############################
    num = 10
    ThreadList = []
    #以下是重点部分:使用threading.Thread类,调用class MyThread(threading.Thread)
    for i in range(1, num):
        t = Sample_zb()
        ThreadList.append(t)
    for t in ThreadList:
        t.start()
    for t in ThreadList:
        t.join()

main()

或者

# /usr/bin/python
# -*- coding:utf-8 -*-

import threading, time

class Sample_zb(threading.Thread):
    
    def __init__(self):
        threading.Thread.__init__(self)
    
    def run(self):
        global n, lock
        time.sleep(1)
        if lock.acquire():
            print (n , self.name)
            n += 1
            lock.release()

if "__main__" == __name__:
    n = 1
    ThreadList = []
    lock = threading.Lock()
    #以下是重点部分:使用threading.Thread类,调用class MyThread(threading.Thread)
    for i in range(1, 8):
        t = Sample_zb() 
        ThreadList.append(t)
    for t in ThreadList:
        t.start()
    for t in ThreadList:
        t.join()

Sample2:

# /usr/bin/python
# -*- coding:utf-8 -*-

import os, json, time
from Queue import Queue
import threading, shutil

pic_list = 'pic.list'
target_dir = 'target_pic'
DEFAULT_THREAD_NUM = 20

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        
    def run():
        global pic_dir
        global target_dir
        global queue, dict3
        value = queue.get()
        for k in range(len(value)):
            try:
                pic_key = value[k]
                pic_dir = dict3[pic_key] 
                shutil.copy(pic_dir, target_dir)
                #os.system('cp ' + pic_dir + ' ' + target_dir)
            except:
                continue
            
if  "__main__" == __name__ :
    n = 1
    i = 0
    n = 0
    ThreadList = []

    wheather_dir_exists(target_dir)
    dict3 = {}

    open_pic_list = open('pic.list', 'r')
    for line in open_pic_list.readlines():
        n += 1
        if n%10000 == 0:
            print n
        line_split = line.split('/')
        get_name = line_split[-1][:-5]
        dict3[get_name] = line.strip('\n')
    
    queue = Queue()
    for i in range(len(not_noly_list)):
        queue.put(not_noly_list[i])
        
 #**以下是重点部分:使用threading.Thread类,调用class MyThread(threading.Thread)**    
    for i in range(1, DEFAULT_THREAD_NUM):
        t = MyThread()
        ThreadList.append(t)
    for t in ThreadList:
        t.start()
    for t in ThreadList:
        t.join()

发布了37 篇原创文章 · 获赞 2 · 访问量 7634

猜你喜欢

转载自blog.csdn.net/bingozb/article/details/98333091
今日推荐