[Python]Two ways to use Threading
来源:互联网 发布:身份证注册软件下载 编辑:程序博客网 时间:2024/05/01 01:56
Python的Lib里,提供了两种使用Threading的方法:
一、函数式:
一、函数式:
import time
import thread
def timer(no, interval):
while True:
print 'Thread: (%d) Time: %s' % (no, time.ctime())
time.sleep(interval)
def test():
thread.start_new_thread(timer, (1, 1))
thread.start_new_thread(timer, (2, 3))
if __name__ == '__main__':
test()
import thread
def timer(no, interval):
while True:
print 'Thread: (%d) Time: %s' % (no, time.ctime())
time.sleep(interval)
def test():
thread.start_new_thread(timer, (1, 1))
thread.start_new_thread(timer, (2, 3))
if __name__ == '__main__':
test()
thread.start_new_thread(function, args[, kwargs])
这个是函数原型, 其中, function是要调用的线程函数;args是传递给你的线程函数的参数,必须是Tuple类型;kwargs是可选参数。
这种线程的结束一般依靠线程函数的自然结束;也可以在线程函数中调用 thread.exit(), 抛出SystemExit exception, 达到退出线程的目的。
二、继承自 threading.Thread类
import threading
import time
class timer(threading.Thread):
def __init__(self, no, interval):
threading.Thread.__init__(self)
self.no = no
self.interval = interval
def run(self):
"重写 run() 方法,实现自己的线程函数"
while True:
print 'Thread Object (%d), Time: %s' % (self.no, time.ctime())
time.sleep(self.interval)
def test():
threadone = timer(1, 1)
threadtwo = timer(2, 3)
threadone.start()
threadtwo.start()
if __name__ == '__main__':
test()
import time
class timer(threading.Thread):
def __init__(self, no, interval):
threading.Thread.__init__(self)
self.no = no
self.interval = interval
def run(self):
"重写 run() 方法,实现自己的线程函数"
while True:
print 'Thread Object (%d), Time: %s' % (self.no, time.ctime())
time.sleep(self.interval)
def test():
threadone = timer(1, 1)
threadtwo = timer(2, 3)
threadone.start()
threadtwo.start()
if __name__ == '__main__':
test()
其中, thread和threading的模块中还包含很多关于多线程编程的东西,如锁、定时器、获得激活线程列表等等。
- [Python]Two ways to use Threading
- Two ways to unlock iphone4
- 20 Ways to Use Gmail Filters
- Two ways to force an IGMP join
- Python Mysql Connect By Two ways
- Three ways to use Perl to open a temporary file
- use python to sendmail
- Use Python to plot
- use python to sendmail
- use python to sendmail
- 10 ways to use keywords in your communications module
- Teaching two russian how to use Oracle.
- Two Quick Ways to Perform ASP.NET Authentication
- [Code Snipper]Two ways to Getting the DPI Value
- Two more accurate ways to get time elapsed than clock()
- Two ways to get HtmlTextWriter for HTML rendering
- Two ways to terminate blocking socket thread gracefully
- Flex Builder Part 1 - Two Ways To Install
- c#活动目录添加用户
- 香港拼音--汉字对照表
- Javascript中的对象
- makefile详解 函数 字符串 文件名 二十一
- C++基本功和 Design Pattern系列 Inheritance VS Delegation
- [Python]Two ways to use Threading
- 使用C#在进度条中显示复制文件的进度
- 函数指针和回调函数浅学
- Hibernate中的经典比喻
- 业务逻辑的强类型化
- HTTP协议与状态
- 有关jndi的单元测试
- ASP.NET实现投票结果的图片进度条显示
- Zero-copy kernel sniffer