Python入门学习(二)线程上

多线程编程

一.创建线程

# -*- coding: cp936 -*-
#多线程编程
import thread
def fun(n):
    for i in range(n):
        print i

thread.start_new_thread(fun,(9,));
thread.start_new_thread(fun,(9,));
thread.start_new_thread(fun,(9,));

import threading
class mythread(threading.Thread):
    def __init__(self,num):
        threading.Thread.__init__(self)
        self.num = num
    def run(self):
        print 'I am ',self.num 

        
def run(x,y):
 for i in range(x,y):
  print i
'''
>>> t1 = threading.Thread(target=run,args=(15,20))
>>> ti.start()
'''





 

二.Thread对象中的方法

1.join方法

join方法:

如果一个线程或者函数的执行过程中调用另一个线程,并且待其完成操作之后才能执行,那么可以调用join方法

import threading
import time
class Mythread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        x=0
        time.sleep(60)
        print self.id

def func():
    t.start()
    for i in range(5):
        print i

   
>>> t=Mythread(2)
>>> func()
0
1
2
3
4

输出结果中没有线程的输出,func函数没有等待线程完成。

 

将程序更改为

import threading
import time
class Mythread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        x=0
        time.sleep(60)
        print self.id

def func():
    t.start()
   <span style="color:#ff0000;"> t.join()
</span>    for i in range(5):
        print i     
>>> t=Mythread(3)
>>> func()
3
0
1
2
3
4

调用join方法,等待线程完成

 

2.isAlive方法

查看线程是否运行

import threading
import time
class Mythread(threading.Thread):
    def __init__(self,id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        x=0
        time.sleep(10)
        print self.id

def func():
    t.start()
    print t.isAlive()
>>> t=Mythread(3)
>>> func()
True
>>> 3


3.用setName方法设置线程名,用getName方法获得线程名

 

4.setDaemon方法

当需要主线程退出时,不管子线程是否完成都随主线程退出,则可以使用Thread对象的setDaemon方法来设置。

import threading
import time
class Mythread(threading.Thread):
    def __init__(self,threadname):
        threading.Thread.__init__(self,name = threadname)

    def run(self):
        time.sleep(5)
        print self.getName()
        
def func1():
    t1.start()
    print 'func1 done'

def func2():
    t2.start()
    print 'func2 done'

t1 = Mythread('t1')
t2 = Mythread('t2')
t2.setDaemon(True)
func1()
func2()




 



 

 

 

 

 

 

 

 

 

 

 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值