2012年8月7日 星期二

threading 初步使用

#簡單使用多線程
import threading
import datetime

#Inherit the threading class to use multi-threading function

class ThreadClass(threading.Thread):
    def run(self):
          #executed 'run' method when the instance 't' start by method t.start()
        now = datetime.datetime.now()
        print "%s says Hello world at time: %s\n" % (self.getName(),datetime.datetime.now())

for i in range(5):
    t = ThreadClass()
    t.start()

>>> 
Thread-1 says Hello world at time: 2012-08-08 00:59:37.715000
Thread-3 says Hello world at time: 2012-08-08 00:59:37.717000
Thread-2 says Hello world at time: 2012-08-08 00:59:37.716000
Thread-4 says Hello world at time: 2012-08-08 00:59:37.718000
Thread-5 says Hello world at time: 2012-08-08 00:59:37.718000

#模仿真實使用線程的結果

import threading
import datetime
import time
import random

class myThread(threading.Thread):
    def run(self):
        now = datetime.datetime.now()
        print 'Execution time:{0} {1}\n'.format(datetime.datetime.now(),self.getName())
        #print 'ThreadName    :{0}\n'.format(self.getName())
        result = []
        for i in range(1,1000):
            result.append(i)
        time.sleep(random.randint(1,3)) # 模擬各線程所耗費的處理時間
        print "ThreadName    :{0} DONE..\n".format(self.getName())


for eachthread in range(1,5):
    t = myThread()
    t.start()
    time.sleep(1)



>>>
Execution time:2012-08-08 01:00:59.385000 Thread-1

Execution time:2012-08-08 01:01:00.385000 Thread-2

ThreadName    :Thread-1 DONE..

Execution time:2012-08-08 01:01:01.385000 Thread-3

ThreadName    :Thread-2 DONE..

Execution time:2012-08-08 01:01:02.385000 Thread-4

ThreadName    :Thread-3 DONE..

ThreadName    :Thread-4 DONE.. 

沒有留言:

張貼留言