import threading
import time
def foo(num):
print('{} is runing \n'.format(num))
time.sleep(3)
print('{} is accomplish \n'.format(num))
t1 = threading.Thread(target=foo, args=(1,)) #創(chuàng)建線程,注意逗號
t2 = threading.Thread(target=foo, args=(2,))
t1.start()
t2.start()
print(t1.getName())
print(t2.getName())
t1.join() #確保線程完成
t2.join()
print('Done')
>>>
================== RESTART: C:\Users\Why Me\Desktop\線程基本.py ==================
1 is runing
Thread-12 is runing
Thread-2
2 is accomplish
1 is accomplish
Done
二钩蚊、創(chuàng)建多個線程
import threading
import time
def foo(num):
print('{} is runing \n'.format(num))
time.sleep(3)
print('{} is accomplish \n'.format(num))
a = []
for i in range(10):
t = threading.Thread(target=foo, args=[i,])
t.start()
a.append(t)
print(t.getName())
for i in a:
i.join()
print('Done')
================= RESTART: C:\Users\Why Me\Desktop\創(chuàng)建多個線程.py =================
Thread-10 is runing
1 is runing
Thread-2
2 is runing
Thread-3
3 is runing
Thread-4
Thread-54 is runing
5 is runing
Thread-6
6 is runing
Thread-7
7 is runing
Thread-8
8 is runing
Thread-9
9 is runing
Thread-10
0 is accomplish
1 is accomplish
2 is accomplish
3 is accomplish
4 is accomplish
5 is accomplish
6 is accomplish
7 is accomplish
8 is accomplish
9 is accomplish
Done
三川蒙、自己寫繼承線程類
import threading
import time
def foo(num):
print('{} is runing \n'.format(num))
time.sleep(3)
print('{} is accomplish \n'.format(num))
class MyThread(threading.Thread):
def __init__(self, num):
super(MyThread,self).__init__() #新式繼承父類__init__
#threading.Thread.__init__(self) #舊式繼承父類__init__
self.num = num
def run(self):
print('{} is runing \n'.format(self.num))
time.sleep(3)
print('{} is accomplish \n'.format(self.num))
t1 = MyThread(1)
t2 = MyThread(2)
t1.start()
t2.start()
================ RESTART: C:\Users\Why Me\Desktop\自己寫繼承線程類.py ================
>>> 1 is runing
2 is runing
1 is accomplish
2 is accomplish