python threads,threading的用法

作者在 2016-10-27 12:39:44 发布以下内容
import threading,time
from time import ctime,sleep
class A(object):
    def b(self):
        print ctime()
        time.sleep(3)
        print ctime()
    def c(self):
        print ctime()
        time.sleep(4)
        print ctime()
    def process(self):
        #args是关键字参数,需要加上名字,写成args=(self,)
        threads = []
        t1 = threading.Thread(target=A.b,args=(self,))
        threads.append(t1)
        t2 = threading.Thread(target=A.c,args=(self,))
        threads.append(t2)
        for t in threads:
            # t.setDaemon(True)
            t.start()
            # t.join()

if __name__ == '__main__':
    P = A()
    P.process()

在非类中调用方法

#coding=utf-8

import threading,time
from time import ctime,sleep
def music(func):
    for i in range(2):
        print "I was listening to %s. %s" %(func,ctime())
        sleep(1)

def move(func):
    for i in range(2):
        print "I was at the %s! %s" %(func,ctime())
        sleep(5)

threads = []
t1 = threading.Thread(target=music,args=(u'cadillac',))
threads.append(t1)
t2 = threading.Thread(target=move,args=(u'lexus',))
threads.append(t2)

if __name__ == '__main__':
    for t in threads:
        t.setDaemon(True)
        t.start()

    print "all over %s" %ctime()

公司 | 阅读 39354 次
文章评论,共0条
游客请输入验证码
浏览2343752次