PYTHON线程知识再研习B

使用threading.Thread模块,也有两种使用方法,可以用类,也可以在实例化对象中传入函数或类实例。

 

PYTHON线程知识再研习B

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/usr/bin/env python
# -*- coding: utf-8 -*-
 
from threading import Thread
import time
 
def run_thread(n):
    for i in range(n):
        print i
         
class race(Thread):
    def __init__(self,threadname,interval):
        Thread.__init__(self,name=threadname)
        self.interval = interval
        self.isrunning = True
 
    def run(self):
        while self.isrunning:
            print 'thread %s is running,time:%s\n' %(self.getName(),time.ctime())
            time.sleep(self.interval)
    def stop(self):
        self.isrunning = False
 
def test():
    t1 = Thread(target=run_thread,args=(5,))
    t1.start()
     
    thread1 = race('A',1)
    thread2 = race('B',2)
    thread1.start()
    thread2.start()
    time.sleep(4)
    thread1.stop()
    thread2.stop()
 
if __name__ == '__main__':
    test()

 

PYTHON线程知识再研习B