python启动线程的方法

本文通过实例演示了Python中使用threading模块进行多线程编程的方法,包括创建和启动线程、获取线程名称以及实现消费者生产者模式等。文章提供了多种创建线程的方式,并展示了如何管理线程以确保程序稳定运行。

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

# coding:utf-8
import threading
import time
#方法二:从Thread继承,并重写run()
class MyThread(threading.Thread):
    def __init__(self,arg):
        super(MyThread, self).__init__()#注意:一定要显式的调用父类的初始化函数。
        self.arg=arg
    def run(self):#定义每个线程要运行的函数
        time.sleep(self.arg)
        print ('the arg is:%s\r\n' % self.arg)

for i in range(4):
    t =MyThread(i)
    t.start()

print ('main thread end!')
# coding:utf-8
import threading
import time
#方法一:将要执行的方法作为参数传给Thread的构造方法
def action(arg):
    time.sleep(arg)
    if(arg==1):
        print( 'the arg is:%s\r\n' %arg)
    if(arg==2):
        print('work2\r\n')
    if(arg==3):
        print('work3\r\n')

for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.start()

print( 'main thread end!')

 

获取线程名字

# coding:utf-8
import threading
import time

def action(arg):
    time.sleep(1)
    print  ('sub thread start!the thread name is:%s\r' % threading.currentThread().getName())
    print ('the arg is:%s\r\n' %arg)
    time.sleep(1)

for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.start()

print ('main_thread end!')
#coding:utf-8
import threading
import time

def action(arg):
    time.sleep(1)
    print  ('sub thread start!the thread name is:%s   \r\n ' % threading.currentThread().getName())
    print( 'the arg is:%s\r\n '  %arg)


thread_list = []    #线程存放列表
for i in range(4):
    t =threading.Thread(target=action,args=(i,))
    t.setDaemon(True)
    thread_list.append(t)

for t in thread_list:
    t.start()

for t in thread_list:
    t.join()
print( 'the main is end ')

 

消费者生产者模式

# encoding: UTF-8
import threading
import time

# 商品
product = None
# 条件变量
con = threading.Condition()

# 生产者方法
def produce():
    global product
    if con.acquire():
        while True:
            if product is None:
                print ( 'produce...')
                product = 'anything'
                # 通知消费者,商品已经生产
                con.notify()
            # 等待通知
            con.wait()
            time.sleep(2)


# 消费者方法
def consume():
    global product
    if con.acquire():
        while True:
            if product is not None:
                print ('consume...')
                product = None
                # 通知生产者,商品已经没了
                con.notify()
            # 等待通知
            con.wait()
            time.sleep(2)
t1 = threading.Thread(target=produce)
t2 = threading.Thread(target=consume)
t2.start()
t1.start()

 

例子来之:https://www.cnblogs.com/tkqasn/p/5700281.html

python--threading多线程总结

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值