1. 程式人生 > >python程序與執行緒小結

python程序與執行緒小結

傳統方式是呼叫2個方法執行1個任務,方法按順序依次執行

# -*- coding:utf-8 -*-
import threading
import time
def run(n):
print('task',n)
time.sleep(3)


if __name__ == '__main__':
run('t1')
run('t2')

多程序例子

2個程序同時併發執行1個任務

# -*- coding:utf-8 -*-
import threading
import time
def run(n):
print('task',n)
time.sleep(3)


if __name__ == '__main__':
t1=threading.Thread(target=run,args=('t1',))
t2=threading.Thread(target=run,args=('t2',))

t1.start()
t2.start()

自己寫一個類繼承繼承threading.Thread
# -*- coding:utf-8 -*-
import threading
import time

class MyThread(threading.Thread):
def __init__(self,n):
super(MyThread,self).__init__()
self.n=n

#這裡面預設就有一個run方法
def run(self):
print('runing task',self.n)


if __name__ == '__main__':
#在主方法通過物件呼叫程序
t1=MyThread('t1')
t2=MyThread('t2')

t1.run()
t2.run()

使用for迴圈啟動多個程序
# -*- coding:utf-8 -*-
import threading
import time
def run(n):
print('task',n)
time.sleep(3)


if __name__ == '__main__':
for i in range(10):
t=threading.Thread(target=run,args=('t-%s'%i,))
t.start()