多线程

Python 使用两个模块来实现多线程,__thread 和 threading,

__thread 模块有一些缺点,threading模块是它的升级版;提供了有一个比thread更高级的API,来提高线程的并发性,能够将多个线程并发运行,共享内存;

setDaemon():setDaemon(True)将线程设置成守护线程,此方法不许再start()方法调用之前设置,如果不设置成守护线程,程序将会无限挂起;

python 中使用线程有两种方式:函数或者用类来包装线程对象。

函数式:调用  __thread模块中的 start_new_thread()函数来产生新线程:

function--线程函数        args -- 传递给线程函数的参数,他必须是个tuple 类型

__thread.start__new__thread(function,args[,kwargs])

import _thread
import time
def print_time(threadName,delay):
    count = 0
    while count < 5:
        time.sleep(delay)
        count += 1
        print('%s:%s'%(threadName,time.ctime(time.time())))


try:
    _thread.start_new_thread(print_time,("Thread-1",2,))
    _thread.start_new_thread(print_time,("Thread-2",4))
except:
    print("Error:无法启动程序")

input('')  #输入后终止程序

while  1:       #无限循环      (如果不写  input 或者 while  程序无法启动)

       pass    

    threading:

            通过使用threading模块,能完成多任务的程序开发,为了让每个线程

封装的更完美,所以使用threading模块时,往往会定义一个新的子类class

只要继承threading.Thread 就可以了。然后重写run方法,

import threading
import time
class MyThread(threading.Thread):
    def run(self):
        for i in range(11):
            print(i)
            time.sleep(2)
t1 = MyThread()
t2 = MyThread()
t1.start()
t2.start()
线程运行的五种状态;
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值