#演示线程的创建和使用
import threading
from time import sleep
import os
a = 1
#线程函数
def music():
global a
print('a = {}'.format(a))
for i in range(5):
sleep(1)
print('播放葫芦娃',os.getpid())
a = 10000 # 查看主线程的a是否修改
#创建线程对象
t = threading.Thread(target = music)
t.start()
for i in range(5):
sleep(1.5)
print('播放灌篮高手',os.getpid())
print('main thread a = {}'.format(a)) # 10000,线程修改的是进程中的变量
t.join()
#线程属性函数演示
from threading import Thread,currentThread
from time import sleep
#线程函数
def fun(sec):
print('线程属性测试')
sleep(sec)
#线程对象的getName属性获取名称
print('%s 线程结束'%currentThread().getName())
#创建线程
threads = []
for i in range(3):
t = Thread(name = 'Worker{}'.format(i),\
target = fun,args = (2,))
threads.append(t)
t.start()
print('is alive :',t.is_alive())
threads[0].setName('Player')
print(threads[0].name) # Player
#回收线程
for i in threads:
i.join()
线程的daemon属性演示
#daemon属性
from threading import Thread
from time import sleep
def fun():
sleep(3)
print('daemon测试')
t = Thread(target = fun)
t.setDaemon(True) # 默认为False时不随着主线程结束而结束
print(t.isDaemon())
t.start()
print('主线程结束') # 程序结束