Python多线程练习

import _thread
import time


#1 线程函数
def print_time(thread_name,delaytime):
count = 0;
while count < 5:
time.sleep(delaytime);
count += 1;
print("%s---%s" % (thread_name,time.ctime(time.time())))
#创建两个线程
try:
# 函数式:调用 _thread 模块中的start_new_thread()函数来产生新线程
# 线程函数,传递给线程函数的参数
_thread.start_new(print_time,("thread-1",2))
_thread.start_new(print_time,("thread-2",4))
except:
print("Erro","无法启动线程")
while 1:
pass
###################################################################
C:python3.7python.exe D:/Python-Test/多线程/多线程.py
thread-1---Tue Nov 28 09:24:26 2017
thread-2---Tue Nov 28 09:24:28 2017
thread-1---Tue Nov 28 09:24:28 2017
thread-1---Tue Nov 28 09:24:30 2017
thread-2---Tue Nov 28 09:24:32 2017
thread-1---Tue Nov 28 09:24:32 2017
thread-1---Tue Nov 28 09:24:34 2017
thread-2---Tue Nov 28 09:24:36 2017
thread-2---Tue Nov 28 09:24:40 2017
thread-2---Tue Nov 28 09:24:44 2017
###################################################################

#2 线程模块
import threading
import time

exitflag = 0

class Mythread(threading.Thread):
    '由类成员、方法、属性组成。从threading.Thread继承创建一个新的子类,并实例化后调用start方法启动新线程,即调用了线程的run方法'
    def __init__(self,threadID,name,counter):
        '_init_方法是一种特殊方法,被称为类的构造方法或者初始化方法,当创建了这个类的实例时就会调用该方法'
        threading.Thread.__init__(self)#self代表类的实例,self在定义类的方法时是必须有的,虽然在调用时不必传入相应的参数
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):
        """
         用以表示线程活动的方法
        """
        print("开始线程:"+self.name)
        print_time(self.name,self.counter,5)
        print("退出线程:" + self.name)
def print_time(threadname,delay,counter):
    while counter:
        if exitflag:
            threadname.exit()
        time.sleep(delay)
        print("%s:%s" % (threadname,time.ctime(time.time())))
        counter -= 1
#创建新线程
thread1 = Mythread(1,"thread-1",1)
thread2 = Mythread(2,"thread-2",2)

#开启新线程
thread1.start()
thread2.start()
thread1.join()
thread2.join()#等待至线程中止。
print("退出主线程")
###################################################################
C:python3.7python.exe D:/Python-Test/多线程/多线程.py
开始线程:thread-1
开始线程:thread-2
thread-1:Tue Nov 28 13:19:51 2017
thread-1:Tue Nov 28 13:19:52 2017
thread-2:Tue Nov 28 13:19:52 2017
thread-1:Tue Nov 28 13:19:53 2017
thread-1:Tue Nov 28 13:19:54 2017
thread-2:Tue Nov 28 13:19:54 2017
thread-1:Tue Nov 28 13:19:55 2017
退出线程:thread-1
thread-2:Tue Nov 28 13:19:56 2017
thread-2:Tue Nov 28 13:19:58 2017
thread-2:Tue Nov 28 13:20:00 2017
退出线程:thread-2
退出主线程
###################################################################
原文地址:https://www.cnblogs.com/acer-haitao/p/7908342.html