[Python]Two ways to use Threading

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()
    

 

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()

其中, thread和threading的模块中还包含很多关于多线程编程的东西,如锁、定时器、获得激活线程列表等等。
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值