---
title: "Python多线程之threading.Thread"
author: "剑锋凛冽"
date: "2012-10-22T09:28:12Z"
tags: []
categories: ["编程语言"]
slug: "python-threading-thread"
draft: false
lastmod: "2012-10-22T09:37:00Z"
id: 1702744
url: "https://swordboy007.iteye.com/blog/1702744"
---

```
print "=======================threading.Thread继承实现多线程============="
import threading
class DemoThread(threading.Thread):
#Python的所有属性必须给出初始值，否则会出现变量名未定义异常
	data=[]
	id=1
	__interval=0
	__stop=False
	def __init__(self,interval=1):
		#不要忘了父类的
		threading.Thread.__init__(self)
		self.__interval=interval
		self.id=DemoThread.getId()
	#覆盖父类run方法定义循环
	def run(self):
		count=0
		#最好用私有属性作为终止条件
		while count<10 and not self.__stop:
			print "Thread-%d,休眠间隔：%d,current Time:%s"%(self.id,self.__interval,time.ctime())
		#使当前线程休眠指定时间，interval为浮点型的秒数，不同于Java中的整形毫秒数
			time.sleep(self.__interval)
			#Python不像大多数高级语言一样支持++操作符，只能用+=实现
			count+=1
			self.data.append(count)
		else:
			print "Thread-%d is over"%self.id
	
	@staticmethod	
	def getId():
		DemoThread.id+=1
		return DemoThread.id
	def stop(self):
		self.__stop=True
newthread=DemoThread(3)
#当主线程结束时，该线程同时结束，只能在start之前设置；false时，不随主线程结束
newthread.setDaemon(False)
newthread.start()
#而这种方式是不需要主线程等待子线程结束的
	
```