Python/Thread/code/test_thread_0715.py

108 lines
2.3 KiB
Python
Raw Normal View History

2024-04-19 19:54:41 +08:00
import threading
from queue import Queue #Thread 無法回傳值,所以要使用 Queue.put() 將要傳回的值存入 Queue再用 Queue.get() 取出
import time
import os
# ----------------------------------------範例1------------------------------
# A報數
def A_Count_off():
for i in range(0,5):
print(f'A : {i}')
time.sleep(0.5)
# B報數
def B_Count_off():
for i in range(5,10):
print(f'B : {i}')
time.sleep(0.5)
thread_list=[A_Count_off,B_Count_off]
thread_num =[]
# for i in range(0,len(thread_list)):
# thread_num.append(threading.Thread(target=thread_list[i]))
#
# for i in range(0,len(thread_num)):
# thread_num[i].start()
# # thread_num[i].join()
#
# for i in range(0,len(thread_num)):
# thread_num[i].join()
# ----------------------------------------範例2------------------------------
def Count_off(code_name):
print('process {} '.format(os.getpid()))
print('thread {} '.format(threading.current_thread().name))
for i in range(0,5):
print(f'{code_name} : {i}')
time.sleep(0.5)
thread_name_list=["A","B","C","D"]
thread_list=[]
# for i in range(0,len(thread_name_list)):
# thread_list.append(threading.Thread(target=Count_off,args=thread_name_list[i]))
# for i in range(0,len(thread_list)):
# thread_list[i].start()
# for i in range(0,len(thread_list)):
# thread_list[i].join()
# ----------------------------------------範例3------------------------------
class Thread_class(threading.Thread):
def __init__(self,code_name):
threading.Thread.__init__(self)
self.code_name = code_name
def run(self):
print('process {} '.format(os.getpid())) # 查看進程
print('thread {} '.format(threading.current_thread().name)) # 查看線程
for i in range(0,5):
print(f'{self.code_name} : {i}')
time.sleep(0.5)
def test_return(self):
return(f'{self.code_name}=END')
thread_name_list=["A","B","C","D"]
thread_list=[]
for i in range(0,len(thread_name_list)):
thread_list.append(Thread_class(thread_name_list[i]))
for i in range(0,len(thread_list)):
thread_list[i].start()
for i in range(0,len(thread_list)):
thread_list[i].join()
for i in range(0,len(thread_list)):
print(thread_list[i].test_return())