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 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
退出主线程
###################################################################
Python多线程练习
生活可以漂泊,可以孤独,但灵魂不能没有归处。
推荐阅读
- 该站点安全证书的吊销信息不可用。是否继续?
- 在Windows Server 2008的桌面上显示“我的电脑”“网上邻居”等图标?
- IE8“开发人员工具”(上)
- 数据链路层(7) 链路层设备
- 网络信息安全法律与政策
- linux 简单记录9 --服务的访问控制列表(ssh,scp,screen)
- linux 简单记录10--使用 vsftpd 服务传输文件(三种模式--匿名模式,本地用户模式,虚拟账号模式),ftp
- Oracle 静默安装的db_install.rsp 文件
- Set,Sorted Set相关命令操作,批量插入及管道,事务
- Oracle AWR,SQL_TRACE,10046,DBMS_PROFILER 等使用