Python知識(shí)分享網(wǎng) - 專業(yè)的Python學(xué)習(xí)網(wǎng)站 學(xué)Python,上Python222
Python多線程編程篇教程(實(shí)例)PDF 下載
匿名網(wǎng)友發(fā)布于:2024-02-16 11:25:28
(侵權(quán)舉報(bào))
(假如點(diǎn)擊沒反應(yīng),多刷新兩次就OK!)

Python多線程編程篇教程(實(shí)例)PDF 下載 圖1

 

 

資料內(nèi)容:

 

多線程編程


其實(shí)創(chuàng)建線程之后,線程并不是始終保持一個(gè)狀態(tài)的,其狀態(tài)大概如下:

     New 創(chuàng)建
     Runnable 就緒。等待調(diào)度
     Running 運(yùn)行
     Blocked 阻塞。阻塞可能在 Wait Locked Sleeping
      Dead 消亡

線程有著不同的狀態(tài),也有不同的類型。大致可分為:
      主線程
      子線程
      守護(hù)線程(后臺(tái)線程)
       前臺(tái)線程
簡(jiǎn)單了解完這些之后,我們開始看看具體的代碼使用了。

 

1、線程的創(chuàng)建

 

Python 提供兩個(gè)模塊進(jìn)行多線程的操作,分別是 thread 和 threading
前者是比較低級(jí)的模塊,用于更底層的操作,一般應(yīng)用級(jí)別的開發(fā)不常用。
因此,我們使用 threading 來舉個(gè)例子:

 

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import time
import threading
class MyThread(threading.Thread):
def run(self):
for i in range(5):
print('thread {}, @number: {}'.format(self.name, i))
time.sleep(1)
def main():
print("Start main threading")
# 創(chuàng)建三個(gè)線程
threads = [MyThread() for i in range(3)]
# 啟動(dòng)三個(gè)線程
for t in threads:
t.start()
print("End Main threading")
if __name__ == '__main__':
main()

 

運(yùn)行結(jié)果:

 

Start main threading
thread Thread-1, @number: 0
thread Thread-2, @number: 0
thread Thread-3, @number: 0
End Main threading
thread Thread-2, @number: 1
thread Thread-1, @number: 1
thread Thread-3, @number: 1
thread Thread-1, @number: 2
thread Thread-3, @number: 2
thread Thread-2, @number: 2
thread Thread-2, @number: 3
thread Thread-3, @number: 3
thread Thread-1, @number: 3
thread Thread-3, @number: 4
thread Thread-2, @number: 4
thread Thread-1, @number: 4

 

注意喔,這里不同的環(huán)境輸出的結(jié)果肯定是不一樣的。