Python之多線程


MyThread類是我自己實現的一個類,繼承自threading模塊中的Thread類,在子類中重寫run方法,當進程調用start方法時候,子類的run方法會被調用!工作需要,現學現賣,獻丑了!

'''
Created on May 28, 2013

@author: Berlin
'''
import threading

class MyThread(threading.Thread):
    def __init__(self, myId, count, mutex):
        self.myId = myId
        self.count = count
        self.mutex = mutex
        threading.Thread.__init__(self)
    
    def run(self):
        for i in range(self.count):
            with self.mutex:
                print('[%s] => %s' % (self.myId, i))

def Main():
    stdoutmutex = threading.Lock()
    threads = []
    for i in range(10):
        thread = MyThread(i, 100, stdoutmutex)
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()
    print('Main thread exiting.')
    
if __name__ == '__main__':
    Main()

謝謝閱讀!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM