thread 和 threading 模块的使用

thread 和 threading 模块的使用

python 虚拟机启动时,多线程处理并没有打开。只支持单线程。

1.thread :thread模块作为低级模块,不推荐直接使用,但使用法简单。
import thread
import time

def worker (index,create_time):
    print (time.time()-create.time),"\t\t",index
    print "thread %d exit ..."%(index)

#启动线程:
for index in range(5):
    thread.start_new_thread(worker,(index,time.time()))//参数:1、函数名,2、函数参数元祖
                                                       //返回值:新生成的线程标示符
print "main thread exit"
常用方法:start_new_thread()
          exit():退出线程,并处罚一个SystemExit异常
          get_ident():获取当前线程标示符


2.threading.Thread类:threading 模块采用继承 threading.Thread 类的方法创建多线程。
例一:
import threading
class ThreadSkeleton(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
    def run(self):
        pass
thread = ThreadSkeleton()
#start()对于每条线程只能启动一次
thread.start()

例二:
import threading
import time
class ThreadDemo(threading.Thread):
    def __init__(self,index,create_time):#参数name可以设置线程的名字
        threading.Thread(self)
        self.index = index
        self.create_time = create_time
    def run(self):
        time.sleep(1)
        print (time.time()-self.create_time),"\t\t",self.index
        print "thread %d exit"%(self.index)


threads = []
for index in range(5):
    thread = ThreadDemo(index,time.time())
    thread.start()
    threads.append(thread)
print "main thread exit"

#join()使主线程在子线程结束后才能运行之后的代码
for thread in threads:
    thread.join()

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值