使用python自帶的執行緒類threading建立執行緒:
import threading
import time
defthread_1_entry
(count)
:while count >0:
print
('count:%d'
% count)
count -=
1 time.sleep(1)
return
defthread_2_entry()
:print
(threading.current_thread(
).name)
return
'''建立執行緒引數說明:
target:執行緒入口函式
name :執行緒名稱
args : 執行緒入口函式的引數
'''thread_1 = threading.thread(target=thread_1_entry, name=
'thread 1'
, args=(5
,))thread_2 = threading.thread(target=thread_2_entry, name=
'thread 2'
)# 啟動執行緒
thread_1.start(
)thread_2.start(
)# 等待執行緒執行完畢退出
thread_1.join(
)thread_2.join(
)
執行結果:
繼承threading類,覆寫run函式:
import threading
import time
class
mythread
(threading.thread)
:def
__init__
(self, name=
none):
threading.thread.__init__(self, name=name)
defrun
(self)
: count =
5while count >0:
print
('%s:%d'
%(self.name, count)
) count -=
1 time.sleep(1)
mythread_1 = mythread(name=
'mythread-one'
)mythread_2 = mythread(name=
'mythread-two'
)mythread_1.start(
)mythread_2.start(
)mythread_1.join(
)mythread_2.join(
)
執行結果:
ends…
python 多執行緒程式設計
一 執行緒基礎 1 建立執行緒 thread模組提供了start new thread函式,用以建立執行緒。start new thread函式成功建立後還可以對其進行操作。其函式原型 start new thread function,atgs kwargs 其引數含義如下 args 元組形式的引...
python 多執行緒程式設計
一 執行緒基礎 1 建立執行緒 thread模組提供了start new thread函式,用以建立執行緒。start new thread函式成功建立後還能夠對其進行操作。其函式原型 start new thread function,atgs kwargs 其引數含義例如以下 args 元組形式...
Python多執行緒程式設計
import threading import time deffunc name time.sleep 3 print 子執行緒 s 啟動 threading.current thread name print hello name print 子執行緒 s 結束 threading.curren...