一、线程的创建、启动
有关线程的一些注意
程序运行时默认创建一个主线程,主线程的线程执行体就是程序中的主程序,即没有放在任何函数中的代码块
主线程默认名为 MainThread,用户启动的多个线程名字依次是 Thread-1, Thread-2,...
当线程被创建后,必须通过调用线程的 start() 方法来启动线程,一旦线程启动了,无论是正常终止还是引发了未捕获的异常,它都处于死亡状态
创建线程的两种方式
直接调用线程构造函数threading.Thread()
继承Thread类重写run()方法
1 直接调用线程构造函数 threading.Thread() 创建线程
import threading, time
#线程要执行的方法
def action(max, delay):
for i in range(max):
#子线程休眠
time.sleep(delay)
print(threading.current_thread().name+'线程第'+str(i)+'次循环\t'+time.asctime())
for i in range(10):
#主线程休眠
time.sleep(1)
print(threading.current_thread().name+'线程第'+str(i)+'次循环\t'+time.asctime())
if i == 5 :
#启动两个子线程,都调用 action() 函数,休眠时间不同
thread_1 = threading.Thread(target=action, args=(10,1), name='thread_1')
thread_2 = threading.Thread(target=action, args=(10,2), name='thread_2')
thread_1.start()
thread_2.start()
print('主线程执行完!\t'+time.asctime())
2 继承Thread类重写run()方法创建线程
只重写Thread类的 __init__() 和 run() 方法
import threading, time
class my_Thread(threading.Thread):
def __init__(self, delay):
threading.Thread.__init__(self)
self.i = 0
self.delay = delay
def run(self):
while self.i < 10:
time.sleep(self.delay)
print(threading.current_thread().name+'线程第'+str(self.i)+'次循环\t'+time.asctime())
self.i += 1
print(threading.current_thread().name+'线程开始\t'+time.asctime())
mythread_1 = my_Thread(2)
mythread_2 = my_Thread(3)
mythread_1.setName('mythread_1')
mythread_2.setName('mythread_2')
mythread_1.start()
mythread_2.start()
#主线程休眠
time.sleep(4)
print(threading.current_thread().name+'线程结束\t'+time.asctime())