python多線程編程簡單例子

來源:互聯網
上載者:User

我喜歡用代碼來理解程式,而不是單單的教程
類 ThreadClass 繼承自 threading.Thread,也正因為如此,您需要定義一個 run 方法,以此執行您在該線程中要啟動並執行代碼。在這個 run 方法中唯一要注意的是,self.getName()是一個用於確定該線程名稱的方法。

 代碼如下 複製代碼

#! /usr/bin/env python
#coding=utf-8
import threading
import datetime
import time
import random
 
class ThreadClass(threading.Thread):
    def run(self):
        now = datetime.datetime.now()
        print "%s says Hello World at time: %s" % (self.getName(),now)
        x = random.randint(1,5)
        print x
        time.sleep(x)
        print 'End %s' % (self.getName())
 
 
for i in range(5):
    t = ThreadClass()
    t.start()
輸出

Thread-1 says Hello World at time: 2014-07-11 16:22:56.820320Thread-2 says Hello World at time: 2014-07-11 16:22:56.820502
 
5
Thread-3 says Hello World at time: 2014-07-11 16:22:56.820777
4
4
 Thread-4 says Hello World at time: 2014-07-11 16:22:56.820988
5
Thread-5 says Hello World at time: 2014-07-11 16:22:56.821276
 
4
End Thread-1
 End Thread-3
 End Thread-5
End Thread-2
End Thread-4

我們可以發現5個多線程的子線程是在並行運作的,而不是順序運作。

要點:
1.定義一個多線程的類

 代碼如下 複製代碼
class ThreadClass(threading.Thread):

2.必須帶有函數run

 代碼如下 複製代碼

def run(self):

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.