Python多线程练习

Posted 喻晓生

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.7\python.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.7\python.exe D:/Python-Test/多线程/多线程.py
开始线程:thread-1
开始线程:thread-2
thread-1:Tue Nov 28 10:27:57 2017
thread-2:Tue Nov 28 10:27:58 2017
thread-1:Tue Nov 28 10:27:58 2017
thread-1:Tue Nov 28 10:27:59 2017
thread-2:Tue Nov 28 10:28:00 2017
thread-1:Tue Nov 28 10:28:00 2017
thread-1:Tue Nov 28 10:28:01 2017
开始线程:thread-1
thread-2:Tue Nov 28 10:28:02 2017
thread-2:Tue Nov 28 10:28:04 2017
thread-2:Tue Nov 28 10:28:06 2017
开始线程:thread-2
退出主线程
###################################################################
























































































以上是关于Python多线程练习的主要内容,如果未能解决你的问题,请参考以下文章

python多线程

[Python3] 043 多线程 简介

python中的多线程和多进程编程

6-4 线程练习题:多线程爬虫

6-4 线程练习题:多线程爬虫

多线程的练习代码 01