import time
import threading
#此时有三个线程:一个是主线程,执行了print("engind..."),t1和t2也是线程
def musice():
print("begin musice %s" % time.ctime())
time.sleep(3) #IO操作,此时CPU切换道game,game遇到IO操作就切换回来,此时就大大缩短了时间,提高CPU利用率
print("stop musice %s" % time.ctime())
def game():
print("begin game %s" % time.ctime())
time.sleep(5)
print("stop game %s" % time.ctime())
'''
#join():
if __name__=='__main__':
t1=threading.Thread(target=musice) #创建了一个线程对象t1
t2=threading.Thread(target=game)
t1.start()
t2.start()
t1.join() #等待t1执行完毕,才执行下面的命令(主线程)
print("ending...") #主线程
'''
threads=[]
t1=threading.Thread(target=musice)
# t1=threading.Thread(target=musice,arges=('参数',)) #有参数的函数需要一个arges=('参数',)
t2=threading.Thread(target=game)
threads.append(t1)
threads.append(t2)
if __name__ == '__main__':
# t1.setDaemon(True) #t1最后还是执行了,因为主线程需要等t2执行完才停止
# t2.setDaemon(True) #t2最后没执行,因为主线程等t1执行完就停止了
for t in threads:
# t.setDaemon(True) #守护,需要在start()前面调用,作用是跟着主线程一起停止
t.start()
print("ending...") #查看没有守护的线程,然后结束了就一起停止,(主线程等待没有被守护的子线程)
#其他方法:
# run():用来表示线程活动的方法
# isAlive():返回线程是否活动,布尔值
# setName():设置线程名
# getName():返回线程名
# start():其实不是真正地启动,只是让线程处于就绪状态,让cpu调用
#threading模块提供的一些方法:
# threading.currentThread():返回当前线程的变量
# threading.enumerate():返回一个正在运行的线程的list,正在运行指启动后和结束前的线程
# threading.active_count():查看有几个线程在使用