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

python基础-线程创建方式

时间:2014-11-02 00:23:22      阅读:256      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   for   sp   div   on   

python中提供了两种创建线程的方式

1.采用thread.start_new_thread(funciton,args..)

2.集成Thread类

 

第一种方式

import thread as t
import time

#Define a function for the thread
def print_time(threadName,delay):
    count=0;
    while count<5:
        time.sleep(delay)
        count+=1
        print "%s(%s): %s " %(threadName,count,time.ctime(time.time()))

#Create two threads as follows
try:
    t.start_new_thread(print_time,("thread-1",2))
    t.start_new_thread(print_time,("thread-2",3))
except:
    print "Error:unable to start thread"

while 1:
    pass

 

2.继承Thread

实现步骤如下

  1. 申明一个Thread类的子类
  2. 覆盖_init_(slef,agrs)方法来增加额外的参数
  3. 实现线程逻辑

 但是有一个奇怪的问题是,run和start方式有很大的差别

import threading 
import time

exitFlag=0

class myThread(threading.Thread):
    #implement thead
    def __init__(self,threadID,name,delay):
        threading.Thread.__init__(self)
        self.threadID=threadID
        self.name=name
        self.delay=delay
       
    def run(self):
        print "Starting "+ self.name
        print_time(self.name,self.delay,5)
        print "Exiting "+ self.name

def print_time(threadName,delay,counter):
    while counter:
        if exitFlag:
            thread.exit()
        time.sleep(delay)
        print ("%s(%s): %s"%(threadName,counter,time.ctime(time.time())))
        counter -=1;

#Create new threads
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",3)


#start
thread1.start()
thread2.start()#run和start不同,why?


while thread2.isAlive():
    if not thread1.isAlive():
        exitFlag = 1
        print "thread1 is over"
    pass
print "Exiting Main Thread"

 

线程同步

python基础-线程创建方式

标签:style   blog   io   color   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/alwaysthinking/p/4067918.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!