1. 程式人生 > >線程調用方式

線程調用方式

線程


1 直接調用


import threading

import time

def sayhi(num): #定義每個線程要運行的函數

print("running on number:%s" %num)

time.sleep(3)

if __name__ == ‘__main__‘:

t1 = threading.Thread(target=sayhi,args=(1,)) #生成一個線程實例

t2 = threading.Thread(target=sayhi,args=(2,)) #生成另一個線程實例

t1.start() #啟動線程

t2.start() #啟動另一個線程

print(t1.getName()) #獲取線程名

print(t2.getName())


2 間接調用


import threading

import time

class MyThread(threading.Thread):

def __init__(self,num):

threading.Thread.__init__(self)

self.num = num

def run(self):#定義每個線程要運行的函數

print("running on number:%s" %self.num)

time.sleep(3)

if __name__ == ‘__main__‘:

t1 = MyThread(1)

t2 = MyThread(2)

t1.start()

t2.start()



線程調用方式