python之最简单的多线程两种写法(类和方法)(threading模块)

多线程指的是:多个线程可以共享一个cpu,cpu在每个线程上运行一会儿,让我们感觉到是多任务在运行,但其实同一时间同一核心只能运算一个东西。

python里多线程在模块threading里

他的用法如下:

import threading
import time


#用方法来写
def run(n):
    print("run",n)
    time.sleep(2)

t1 = threading.Thread(target=run,args=("1",))
t2 = threading.Thread(target=run,args=("2",))

t1.start()
t2.start()

#-----------------------------------------------------
#用类来写
class myThread(threading.Thread):
    def __init__(self, n):
        super(myThread, self).__init__()
        self.n = n
    def run(self):
        print("runing task", self.n)

t1 = myThread("1")
t2 = myThread("2")

t1.start()
t2.start()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值