threading 多線程

# coding:utf-8
import time

from threading import Thread


def foo(x):#這裏能夠帶參數def foo(x)
    print "foo start 啓動耗時".decode('utf-8'), time.ctime()
    time.sleep(x)
    print "foo start 運行結束:".decode('utf-8'), time.ctime()
    return "aaa"
def soo(x):
    print "soo start 啓動耗時".decode('utf-8'), time.ctime()
    time.sleep(x)
    print "soo start 運行結束".decode('utf-8'), time.ctime()
    return "bbb"


class MyThread1(Thread):
    def __init__(self, number):
        Thread.__init__(self)
        self.num=number

    def run(self):
        print "run() start foo", time.ctime()
        self.result = foo(self.num)#模擬耗時

    def get_result(self):
        return self.result#獲取返回值

class MyThread2(Thread):
    def __init__(self, number):
        Thread.__init__(self)
        self.num = number

    def run(self):
        print "run() start soo", time.ctime()
        self.result = soo(self.num)

    def get_result(self):
        return self.result

thd1 = MyThread1(3)
thd2 = MyThread2(5)
print "pre start\n\t"
thd1.start()
print "thd1 started\n\t"
thd2.start()
print "\n\t"
print "thd2 started\n\t"
thd1.join()
thd2.join()
print " \n\t"
print "all done"
print thd1.get_result(), time.ctime()
print thd2.get_result(), time.ctime()
相關文章
相關標籤/搜索