码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记- Python threading模块

时间:2016-03-16 07:09:17      阅读:178      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!