備忘錄_20160105(定位) 修改 回首頁

程式 2025-02-04 08:09:27 1738627767 100
python 多執行緒

python 多執行緒

import threading
import time

i=0

def print_every_three_seconds():
    
    global i
    
    while True:
        
        if i>5:
          print("執行緒1 stopped")
          break
        
        print("執行緒1: 每 3 秒執行一次=="+str(i))
        time.sleep(3)

def print_every_one_second():
    
    global i
    i=i+1
    
    while True:
        
        if i>5:
          print("執行緒2 stopped")
          break
        
        print("執行緒2: 每 1 秒執行一次--"+str(i))
        time.sleep(1)

# 創建兩個執行緒
t1 = threading.Thread(target=print_every_three_seconds)
t2 = threading.Thread(target=print_every_one_second)

# 啟動執行緒
t1.start()
t2.start()

# 讓主執行緒保持運行
t1.join()
t2.join()

print('兩個執行緒都停下來了')