Python--线程组(threading)

Python支持两种创建多线程的方式:

  • 通过threading.Thread()创建
  • 通过继承threading.Thread()类创建

1、通过threading.Thread()创建:

Thread()的语法如下:

threading.Thread(group = None,target=None,name=None,args=(),kwargs=(),*,daemon=None)

  • group:必须为None,与ThreadGroup类相关,一般不使用。
  • target:线程调用的对象,就是目标函数。
  • name:为线程命名,默认是Thread-x,x是序号,由1开始,第一个创建的线程的名字就是Thread-1.
  • args:为目标函数传递实参,元组。
  • kwargs:为目标函数传递关键字参数,字典。
  • daemon:用来设定线程是否随主线程退出而退出。

示例1:

import threading  # 导入线程组模块

def test_1(a, b):
    for i in range(a, b):
        print(i)

T1 = threading.Thread(name="t1", target=test_1, args=(1, 10))#通过threading.Thread()创建
T2 = threading.Thread(name="t2", target=test_1(10, 20))
T1.start()  # 启动线程1
T2.start()  # 启动线程2

2、通过继承threading.Thread()类创建:

threading.Thread()是一个类,可以继承。

示例2:

import threading  # 导入线程组模块

class mythread(threading.Thread):  # 继承threading.Thread类创建
    def run(self):  # 重写父类的run方法
        for i in range(10):
            print(i)

thread1 = mythread()
thread2 = mythread()
thread1.start()
thread2.start()

3、主线程:

创建线程时有一个daemon属性,可以用来判断主线程,当daemon设置为Flase时,子线程不会随主线程退出而退出,主线程会一直等着子线程执行完。当daemon设置为Ture时,主线程结束,其他子线程会强制结束。

示例3:

import threading
from time import sleep

def test_1():
    sleep(3)
    for i in range(5):
        print(i)

t1 = threading.Thread(target=test_1, daemon=False)
t1.start()

print("主线程结束")

结果1:

 
分析:daemon设置Flase时,主线程输出“主线程结束”后,会等待子线程执行完再退出。

结果2:


分析:daemon设置为Ture时,主线程输出“主线程结束”后,会强制子线程退出。

 

4、阻塞线程

多线程提供了一个阻塞线程方法join(),在一个线程中调用另一个线程的join()方法,调用者将被阻塞,知道被调用的线程执行结束或者终止。句法:join(timeout=None),timeout参数指定调用者等待多久,如没有设置则一直等待到被调用线程结束。其中,一个线程可以被join多次。

示例4:

结果:

分析:在调用主线程时,由于添加了join ()方法,所以调用了子线程test_1,等子线程test_1执行结束后再执行主线程的print输出。

5、判断线程是否活动

使用is_alive()方法判断线程是否活动

示例5.1:

 结果:

 分析:在线程没有使用start()方法启动前,判断线程是否活动所以输出了Flase;线程启动后判断线程是否活动输出了Ture。使用getName()方法获取线程名称,在创建线程时并没有使用name属性给线程命名,所以线程的默认名字是Thread-X形式。在代码运行期间也可以使用setName()方法更改线程名字。

示例5.2:

结果:

 

6、线程同步

6.1线程锁

Python中threading模块提供了Rlock锁(可重入锁)解决方法,某一时间只能让一个线程操作的语句放到Rlock的acquire()方法和release()方法之间,即acquire相当于上锁,release相当于解锁。

示例6.1:

结果:

 

6.2、条件锁

Python中threading提供一个条件锁方法condition(),用法:con = threading.Condition().

示例6.2:

import threading
import time

products = []
condition = threading.Condition()

class Consumer(threading.Thread):
    def consumer(self):
        global condition
        global products

        condition.acquire()  # 设置条件锁
        if len(products) == 0:
            condition.wait()
            print("消费者提醒:没有产品去消费了!")
            # condition.notify()
        products.pop()
        print("消费者提醒:消费一个产品!")
        print('消费者提醒:还能消费的产品数为 :%s' % (str(len(products))))
        condition.notify()
        condition.release()

    def run(self):
        for i in range(100):
            time.sleep(4)
            self.consumer()


class Producer(threading.Thread):
    def produce(self):
        global condition, products

        condition.acquire()  # 设置条件锁
        if len(products) == 10:
            condition.wait()
            print("生产者提醒:生产的产品数为" + str(len(products)))
            print("生产者提醒:停止生产!")
            # condition.notify()  # 线程通知
        products.append(1)
        print("生产者提醒:产品总数为" + str(len(products)))
        condition.notify()  # 线程通知
        condition.release()  # 线程解锁

    def run(self):
        for i in range(100):
            time.sleep(1)  # 每秒钟生产一个产品
            self.produce()

produce = Producer()  # 生产者实例
consumer = Consumer()  # 消费者实例
produce.start()
consumer.start()
produce.join()  # 阻塞线程
consumer.join()  # 阻塞线程

 分析:上述代码使用time.sleep()方法每一秒生产一个产品,每四秒消费一个产品;当产品上限达到10后就停止生产,并调用wait()等待线程通知;可消费的产品数量为0时停止消费,并调用wait等待线程通知。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值