多线程之start()和run()
在实例调用的函数中加入打印当前线程的名字,分别用start()方法和run()方法启动线程检查有什么区别:
start()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import threadingimport timedef worker(): count = 1 while True: if count >= 6: break time.sleep(1) count += 1 print("thread name = {}".format(threading.current_thread().name))#当前线程名t = threading.Thread(target=worker,name="MyThread")t.start()print("===end===")运行结果:===end===thread name = MyThread #thread name = MyThreadthread name = MyThreadthread name = MyThreadthread name = MyThread |
从上面例子中打印的线程名字来看,使用start()方法启动的线程名是我们定义线程对象时设置的name="MyThread"的值,如果没有设置name参数值,则会打印系统分配的Thread-1,Thread-2...这样的名称。
run()方法
|
|
import threadingimport timedef worker(): count = 1 while True: if count >= 6: break time.sleep(1) count += 1 print("thread name = {}".format(threading.current_thread().name))t = threading.Thread(target=worker,name="MyThread")t.run()print("===end===")运行结果:thread name = MainThread #thread name = MainThreadthread name = MainThreadthread name = MainThreadthread name = MainThread===end=== |
上面例子中,使用的是用run()方法启动线程,它打印的线程名是MainThread,也就是主线程。
再看下多线程时的例子:
start():
|
|
import threadingimport timedef worker(): count = 1 while True: if count >= 6: break time.sleep(1) count += 1 print("thread name = {}, thread id = {}".format(threading.current_thread().name,threading.current_thread().ident))t1 = threading.Thread(target=worker,name="t1")t2 = threading.Thread(target=worker,name='t2')t1.start()t2.start()print("===end===")运行结果:===end===thread name = t1, thread id = 6032thread name = t2, thread id = 880thread name = t1, thread id = 6032thread name = t2, thread id = 880thread name = t2, thread id = 880thread name = t1, thread id = 6032thread name = t1, thread id = 6032thread name = t2, thread id = 880thread name = t2, thread id = 880thread name = t1, thread id = 6032 |
上面例子中,start()方法启动了两个新的子线程并交替运行,每个子进程ID也不同。
run():
|
|
import threadingimport timedef worker(): count = 1 while True: if count >= 6: break time.sleep(1) count += 1 print("thread name = {}, thread id = {}".format(threading.current_thread().name,threading.current_thread().ident))t1 = threading.Thread(target=worker,name="t1")t2 = threading.Thread(target=worker,name='t2')t1.run()t2.run()print("===end===")运行结果:thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000thread name = MainThread, thread id = 2000===end=== |
上面例子中,两个子线程都用run()方法启动,但却是先运行t1.run(),运行完之后才按顺序运行t2.run(),两个线程都工作在主线程,没有启动新线程,因此,run()方法仅仅是普通函数调用。
一个进程中至少有一个线程,并作为程序的入口,这个线程就是主线程。
一个进程至少有一个主线程,其它线程称为工作线程。
总结:
好了,从上面四个小例子,我们可以总结出:
- start() 方法是启动一个子线程,线程名就是我们定义的name
- run() 方法并不启动一个新线程,就是在主线程中调用了一个普通函数而已。
因此,如果你想启动多线程,就必须使用start()方法

浙公网安备 33010602011771号