码迷,mamicode.com
首页 > 编程语言 > 详细

多线程应用-类(thread)

时间:2016-04-15 18:26:23      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:

 

# -*- coding: UTF-8 -*-
from time import ctime,sleep
import threading,datetime
from Queue import Queue

class pdc(threading.Thread):
    def __init__(self,t_name):
        threading.Thread.__init__(self,name=t_name)
        #self.name=‘aaa‘ #此时self还不是Thread,为string格式
    def run(self): #run()方法继承于threading,需要重写定义自己的内容
        self.setName(b+str(i)) #self.setName(‘bbb‘) #此时self是Thread,可以通过 print dir(self) 查看所具有的属性/方法
        print %s: %s is producing %d to the queue. %(ctime(),self.getName(),i)
        sleep(1)

if __name__ == __main__:
    threads=[]
    for i in range(5):
        t = pdc(p+str(i))
        t.start()
        threads.append(t)
    for t in threads:
        t.join()

返回结果:

Fri Apr 15 17:19:22 2016: b1 is producing 1 to the queue.
Fri Apr 15 17:19:22 2016: b1 is producing 1 to the queue.
Fri Apr 15 17:19:22 2016: b2 is producing 2 to the queue.
Fri Apr 15 17:19:22 2016: b4 is producing 4 to the queue.
Fri Apr 15 17:19:22 2016: b4 is producing 4 to the queue.

 

多线程应用-类(thread)

标签:

原文地址:http://www.cnblogs.com/dreamer-fish/p/5396178.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!