首页 > 编程语言 > 详细

Python学习笔记- Python threading模块

时间:2016-03-16 07:07:37      阅读:250      评论:0      收藏:0      [点我收藏+]

Python threading模块

直接调用

# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time

def sayhi(num):
    print("running on number:%s" % num)
    time.sleep(3)

if __name__ ==__main__:

    #生成两个线程实例
     t1 = threading.Thread(target=sayhi,args=(1,))
     t2 = threading .Thread(target = sayhi,args=(2,))

     #启动两个线程
     t1.start()
     t2.start()

    #打印线程名
     print(t1.getName())
     print(t2.getName())

继承调用

 

import threading
import time
class MyThread(threading.Thread):
    def __init__(self,num):
        # super(Mythread,self).__init__(self)
        threading.Thread.__init__(self)
        self.num = num

    def run(self):

        print(running on number%s %self.num)
        time.sleep(3)

if __name__ == __main__:

    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()

批量处理多线程及等待

import threading
import time

def sayhi(num):

        print(running on number%s %num)
        time.sleep(5)

if __name__ == __main__:
    ‘‘‘
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()
    ‘‘‘
t_list=[] #用于存储实例
for i in range(100):
  t = threading.Thread(target=sayhi,args =[i,] ) #循环创建实例
  t.start()
  t_list.append(t) #将创建的实力添加到列表
for i in t_list:#循环列表中的创建的实例
    i.join() #在每个列表后面添加等待
print(##############main###############)

 

Python学习笔记- Python threading模块

原文:http://www.cnblogs.com/luoye00/p/5281914.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!