python之執行緒入門

2021-10-10 16:41:55 字數 1396 閱讀 2442

import threading

import time

class

mythread

(threading.thread)

:def

__init__

(self, threadid, threadname, counter)

: threading.thread.__init__(self)

self.threadid = threadid

self.threadname = threadname

self.counter = counter

defrun(self)

:print

("執行緒開始:"

, self.threadname)

lock.acquire(

)#使用self呼叫該物件中的方法。py中的屬性,方法時屬於該類還是屬於物件,呼叫物件的屬性/方法用self等同於this。

self.timemethod(self.threadname, self.counter)

lock.release(

)def

timemethod

(self, threadname, counter)

: delay =

1while counter:

time.sleep(delay)

print

(threadname, time.time())

counter -=

1if __name__ ==

'__main__'

: lock = threading.lock(

) thread1 = mythread(1,

"thread_1",2

) thread2 = mythread(2,

"thread_2",2

) thread1.start(

) thread2.start(

) thread1.join(

) thread2.join(

)print

("main thread out"

)

執行結果:

執行緒開始: thread_1

執行緒開始: thread_2

thread_1 1606116927.151993

thread_1 1606116928.1526074

thread_2 1606116929.15364

thread_2 1606116930.1542966

main thread out

process finished with exit code 0

python 多執行緒入門

import threading from time import sleep deflol for i in range 3 print loling.d i sleep 1 defweiwa for i in range 3 print weiwa.d i sleep 1 if name mai...

python之執行緒

前言 python的thread模組是比較底層的模組,python的threading模組是對thread做了一些包裝的,可以更加方便的被使用 實現執行緒的方法 使用threading模組import threading import time 注意 在寫迴圈的時候for i in range 5 ...

python之執行緒

程序和執行緒都是虛擬單位,只是為了我們更加方便的描述問題 3.1 方式一 from threading import thread import time def task name print f is running time.sleep 1 print f is stopping 開執行緒的 ...