import time
# 單執行緒
def sayHello(index):
print('hello!', index)
time.sleep(1)
print('執行完成')
for i in range(5):
sayHello(i)
複製程式碼
結果:
例子中看單執行緒程式執行呢就是一個接著一個執行
多執行緒:
import time
import threading
def sayHello(index):
print('hello!', index)
time.sleep(1)
print('執行完成')
for i in range(5):
t1 = threading.Thread(target=sayHello, args=(i,))
t1.start()
複製程式碼
Thread(group=None, target=None, name=None, args=(), kwargs=None, *, daemon=None)
|*group* should be None; reserved for future extension when a ThreadGroup
|class is implemented.
|
|*target* is the callable object to be invoked by the run()
|method. Defaults to None, meaning nothing is called.
|
|*name* is the thread name. By default, a unique name is constructed of
|the form "Thread-N"where N is a small decimal number.
|
|*args* is the argument tuple for the target invocation. Defaults to ().
|
|*kwargs* is a dictionary of keyword arguments for the target
|invocation. Defaults to {}.
複製程式碼
target就是執行緒啟動後執行的函式
args和kwargs都是這個函式的引數,args是元組型別,kwargs是關鍵字型別引數。
name是給這個執行緒的名字,如果不傳就是Thread-1, Thread-2....
它還有一些方法:
run(): 執行執行緒中的方法。
start(): 啟動執行緒。
join(): 等待執行緒結束。
isAlive(): 返回執行緒是否活動的。
getName(): 返回執行緒名。
setName(): 設定執行緒名。
threading.currentThread
threading.currentThread可以獲得當前的執行緒資訊,例子:
import time
from threading import Thread, currentThread
def sayHello(index):
print(currentThread().getName(), index)
time.sleep(1)
print('執行完成')
for i in range(5):
t1 = Thread(target=sayHello, kwargs={'index': 1})
t1.start()
複製程式碼
from threading import Thread
a = 0
def change_num(num):
global a
a += 1
a -= 1
def run_thread(num):
for i in range(100000):
change_num(num)
t1 = Thread(target=run_thread, args=(1,))
t2 = Thread(target=run_thread, args=(2,))
t1.start()
t2.start()
t1.join()
t2.join()
print(a)
複製程式碼