第一曲
简单使用
# 方法一
import threading
import time
def func(id):
print('threading:%s' % id)
time.sleep(2)
print('%s done...' % id)
t1 = threading.Thread(target=func,args=(1,)) #创建线程对象
t2 = threading.Thread(target=func,args=(2,))
t1.start() #启动线程
t2.start()
#方法二
import threading
import time
class my_thread(threading.Thread):
def __init__(self,name,id):
super(my_thread, self).__init__()
self.name = name
self.id = id
def run(self): # 必须命名一个run()方法,线程对象调用start()方法时会执行run()的内容
print('thread id:%s, name:%s' % (self.name,self.id))
time.sleep(2)
t1 = my_thread('t1',1)
t2 = my_thread('t2',2)
t1.start()
t2.start()
一些函数
start()
启动线程的函数
join()
主线程等待子线程执行完毕在向下执行
current_thread()
目前线程的信息
active_count()
目前线程的数目
import threading,time
class my_thread(threading.Thread):
def __init__(self,num):
super(my_thread,self).__init__()
self.num = num
def run(self):
print('Thread:',self.num)
# print('thread info:',threading.current_thread())
time.sleep(2)
thread_obj_list = []
for i in range(50):
t = my_thread(i)
thread_obj_list.append(t)
t.start()
print('active threads:',threading.active_count())
for t in thread_obj_list:
t.join()
print('active threads:',threading.active_count())
print('main program exit...')