建立一个生产者随机产生整数插入队列,建立两个消费者,一个不停地取奇数,另一个不停地取偶数。
原理:面向对象地抽象线程需要自定义一个类继承Thread类。比如自定义class MyThread(Thread)。这个类的一个实例就是代表了一个线程,然后通过重载这个类中的run方法(是run,不是start!!但start的动作确实就是调用run)来执行具体的操作。此时锁可以作为一个构造方法的参数,将一个锁传进不同的实例中以实现线程锁控制。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
' a test module '
__author__ = 'Zhang Shuai'
import queue, threading
import random, time
class Producter(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.queue = queue
def run(self):
for i in range(10):
random_num = random.randint(1, 99)
print("thread {} is running,time is {}, put {} in queue".format(self.getName(), time.ctime(), random_num))
self.queue.put(random_num)
time.sleep(0.4)
print("threading {} is finished".format(self.getName()))
class consumer_odd(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.queue = queue
def run(self):
try:
while 1:
num = self.queue.get(1, 10)
if num % 2 != 0:
print("thread {} is running,time is {}, get {} from queue".format(self.getName(), time.ctime(), num))
else:
self.queue.put(num)
except Exception as e:
print("threading {} is finished".format(self.getName()))
class consumer_even(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.queue = queue
def run(self):
try:
while 1:
num = self.queue.get(1, 6)
if num % 2 == 0:
print("thread {} is running,time is {}, get {} from queue".format(self.getName(), time.ctime(), num))
else:
self.queue.put(num)
except Exception as e:
print("threading {} is finished".format(self.getName()))
def main():
q = queue.Queue()
p = Producter("producter", q)
o = consumer_odd("comuser_odd", q)
e = consumer_even("consumer_even", q)
p.start()
o.start()
e.start()
p.join()
e.join()
o.join()
if __name__ == '__main__':
main()
print("project is finished")
Thread类还有以下的一些方法,自定义的类也可以调用
- getName()
- setName(…) //其实Thread类在构造方法中有一个name参数,可以为相应的线程取一个名字。这两个方法就是相关这个名字属性的
isAlive() 一个线程从start()开始到run()结束的过程中没有异常,则其实alive的。
setDaemon(True/False) 是否设置一个线程为守护线程。当你设置一个线程为守护线程之后,程序不会等待这个线程结束再退出程序,可参考http://blog.csdn.net/u012063703/article/details/51601579
除了Thread类,threading中还有以下一些属性,简单介绍一下:
Timer类,Timer(int,target=func) 和Thread类类似,只不过它在int秒过后才以target指定的函数开始线程运行
currentThread() 获得当前线程对象
activeCount() 获得当前活动的线程总个数
enumerate() 获得所有活动线程的列表
settrace(func) 设置一跟踪函数,在run执行前执行
setprofile(func) 设置一跟踪函数,在run执行完毕之后执行
文章参考:http://www.cnblogs.com/franknihao/p/6627857.html
更 多 :http://www.cnblogs.com/tkqasn/p/5700281.html