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

基于类和基于函数的python多线程样例

时间:2016-11-22 11:58:42      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:print   div   run   pytho   com   技术   start   lag   target   

不断的练,加深记忆吧。

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


import threading 
import time


exitFlag = 0

def first_function():
    print (threading.currentThread().getName() +            str( is Starting \n))
    time.sleep(2)
    print (threading.currentThread().getName() +            str( is Exiting \n))


def second_function():
    print (threading.currentThread().getName() +            str( is Starting \n))
    time.sleep(2)
    print (threading.currentThread().getName() +            str( is Exiting \n))

def third_function():
    print (threading.currentThread().getName() +            str( is Starting \n))
    time.sleep(2)
    print (threading.currentThread().getName() +            str( is Exiting \n))

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

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


if __name__ == "__main__":
    t1 = threading.Thread         (name=first_function, target=first_function)
    t2 = threading.Thread         (name=second_function, target=second_function)
    t3 = threading.Thread         (name=third_function, target=third_function)

    t1.start()
    t2.start()
    t3.start()
    t1.join()
    t2.join()
    t3.join()

    thread1 = myThread(1, "Thread-1", 1)
    thread2 = myThread(2, "Thread-2", 2)
    thread1.start()
    thread2.start()
    thread1.join()
    thread2.join()
    print("Exiting Main Thread")
    
    

技术分享

基于类和基于函数的python多线程样例

标签:print   div   run   pytho   com   技术   start   lag   target   

原文地址:http://www.cnblogs.com/aguncn/p/6088201.html

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