threading:線程創建、啟動、睡眠、退出


1.方法一:將要執行的函數作為參數傳遞給threading.Thread()

import threading

import time

 

def func(n):

    global count

    time.sleep(0.1)

    for i in range(n):

        count += 1

 

if __name__ == '__main__':

    count = 0

    threads = []

    for i in range(5):

        threads.append(threading.Thread(target=func, args=(1000,)))

    for t in threads:

        t.start()

    time.sleep(5)

    print('count:', count)

2.方法二:繼承treading.Thread()類,並重寫run()

import threading

import time

 

class myThread(threading.Thread):

    def __init__(self, n):

        threading.Thread.__init__(self)

        self.myThread_n = n

    def run(self):

        global count

        for i in range(self.myThread_n):

            count += 1

 

if __name__ == '__main__':

    cout = 0

    threads = []

    for i in range(5):

        threads.append(myThread(1000))

    for t in threads:

        t.start()

    time.sleep(5)

    print('count:', count)

 


免責聲明!

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



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