Python学习笔记:线程

本文详细介绍了Python中线程的创建、管理和使用线程池进行并发任务处理的方法。通过实例演示了如何创建子线程、等待线程结束、查看活动线程数以及实现线程池抢票系统的全过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建一个子线程

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg):
    while 1:
        print arg,
        time.sleep(1)
        sys.stdout.flush()

t = Thread(target = thread_fun, args = ('*'))
t.start()
while 1:
    print '.',
    time.sleep(1)
    sys.stdout.flush()

运行结果:
在这里插入图片描述

注:需要kill -9杀死子线程

2.等待子线程结束

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg1,arg2):
    while arg2:
        print arg1,
        time.sleep(1)
        sys.stdout.flush()
	arg2 -= 1

t = Thread(target = thread_fun, args = ('*',20))
t.start()
i = 10
while i:
    print '.',
    time.sleep(1)
    sys.stdout.flush()
    i -= 1
t.join()

运行结果:
在这里插入图片描述

3.线程模块

#!/user/bin/python
#coding:utf-8
from threading import *
import sys
import time
def thread_fun(arg1,arg2):
    while arg2:
        print arg1,
        time.sleep(1)
        sys.stdout.flush()
	arg2 -= 1
print currentThread()
print '现在的活动线程数是:%d'%activeCount()
t = Thread(target = thread_fun, args = ('*',20))
t.start()
print '新创建的线程名是:',t.getName()
print '现在的活动线程数是:%d'%activeCount()
i = 10
while i:
    print '.',
    time.sleep(1)
    sys.stdout.flush()
    i -= 1
print '现在的活动线程数是:%d'%activeCount()
t.join()
print '现在的活动线程数是:%d'%activeCount()

运行结果:
在这里插入图片描述

4.线程池的实现

参考文献:https://blog.youkuaiyun.com/yongh701/article/details/51313119

#!/user/bin/python
#coding:utf-8
from threading import *
mutex_lock = RLock()
import sys
import time
import random
ticket = 700
class mythread(Thread):
    thread_counter = 0
    def __init__(self,name,index):
        Thread.__init__(self)
        self.name = name
        self.index = index
        mythread.thread_counter += 1
    def run(self):
        global ticket
        global mutex_lock
        tm = random.randint(1,999)/1000.0
        time.sleep(tm)
        mutex_lock.acquire()
        if ticket > 0:
            ticket -= 1
            print self.index,'抢到票了...'
            print '还剩%d张票...'%ticket
        else:
            print self.index,'没有抢到票...'
        mutex_lock.release()
threads = []
for i in range(1,1000):
    t = mythread('thread-'+str(i),i)
    threads.append(t)
for i in threads:
    i.start()
    print '\033[1;32m',i.index,'\033[0m',
    pass
for i in threads:
    i.join()
    print '\033[1;31m',i.index,'\033[0m',
    pass

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值