Python多線程編程簡單介紹_python

來源:互聯網
上載者:User

建立線程

格式如下

複製代碼 代碼如下:

threading.Thread(group=None, target=None, name=None, args=(), kwargs={})

這個構造器必須用關鍵字傳參調用
- group 線程組
- target 執行方法
- name 線程名字
- args target執行的元組參數
- kwargs target執行的字典參數

Thread對象函數

函數 描述
start() 開始線程的執行
run() 定義線程的功能的函數(一般會被子類重寫)
join(timeout=None) 程式掛起,直到線程結束;如果給了 timeout,則最多阻塞 timeout 秒
getName() 返回線程的名字
setName(name) 設定線程的名字
isAlive() 布爾標誌,表示這個線程是否還在運行中
isDaemon() 返回線程的 daemon 標誌
setDaemon(daemonic) 把線程的 daemon 標誌設為 daemonic(一定要在調用 start()函數前調用)

常用樣本

格式

複製代碼 代碼如下:

import threading

def run(*arg, **karg):
    pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()


執行個體
複製代碼 代碼如下:

#!/usr/bin/python
#coding=utf-8

import threading
from time import ctime,sleep

def sing(*arg):
    print "sing start: ", arg
    sleep(1)
    print "sing stop"


def dance(*arg):
    print "dance start: ", arg
    sleep(1)
    print "dance stop"

threads = []

#建立線程對象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)

t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)

#開始線程
t1.start()
t2.start()

#等待線程結束
for t in threads:
    t.join()

print "game over"


輸出
複製代碼 代碼如下:

sing start:  ('raise me up',)
dance start:  ('Rup',)
sing stop
dance stop
game over

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.