1. 線程是什麼多線程
2. 線程和進程的區別併發
3.多線程的舉例ide
方式一:函數式開啓線程函數
1 from threading import Thread 2 from time import sleep 3 4 5 def read(name): 6 print('%s start read!' % name) 7 sleep(3) 8 print('%s stop read!' % name) 9 10 11 if __name__ == '__main__': 12 t = Thread(target=read,args=('sjingx',)) 13 t.start() 14 print('主線程')
方式二:類繼承方式開啓線程工具
1 from threading import Thread 2 from time import sleep 3 4 5 class Read(Thread): 6 def __init__(self, name): 7 super().__init__() 8 self.name = name 9 10 def run(self): 11 print('%s start read!' % self.name) 12 sleep(3) 13 print('%s stop read!' % self.name) 14 15 16 if __name__ == '__main__': 17 r = Read('sjingx') 18 r.run() 19 print('主線程')
1. 基於多線程實現併發的套接字通訊。spa
2. 編寫一個簡單的文本處理工具,具有三個任務,一個接收用戶輸入,一個將用戶輸入的內容格式化成大寫,一個將格式化後的結果存入文件。線程
在主進程下開啓線程code
import time from multiprocessing import Process from threading import Thread # 開啓進程 class Read(Process): def __init__(self, name): super().__init__() self.name = name def run(self): print('%s start read' % self.name) if __name__ == '__main__': t1 = time.time() r = Read('sjingx') r.start() print('主進程') t2 = time.time() print(t2-t1) # 結果是: # 主進程 # 0.024098873138427734 # sjingx start read
在主進程下開啓進程對象
import timefrom threading import Thread # 開啓線程 class Read(Thread): def __init__(self, name): super().__init__() self.name = name def run(self): print('%s start read' % self.name) if __name__ == '__main__': t1 = time.time() r = Read('sjingx') r.start() print('主線程') t2 = time.time() print(t2-t1) # 運行結果: # sjingx start read # 主線程 # 0.001003265380859375