import threading
import time
class MyThread(threading.Thread):
def __init__(self, threadId, threadName, counter):
threading.Thread.__init__(self)
self.threadId = threadId
self.threadName = threadName
self.counter = counter
def run(self):
print("线程开始:", self.threadName)
lock.acquire()
#使用self调用该对象中的方法。py中的属性,方法时属于该类还是属于对象,调用对象的属性/方法用self等同于this。
self.timeMethod(self.threadName, self.counter)
lock.release()
def timeMethod(self, threadName, counter):
delay = 1
while counter:
time.sleep(delay)
print(threadName, time.time())
counter -= 1
if __name__ == '__main__':
lock = threading.Lock()
thread1 = MyThread(1, "Thread_1", 2)
thread2 = MyThread(2, "Thread_2", 2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print("main thread out")
运行结果:
线程开始: Thread_1
线程开始: Thread_2
Thread_1 1606116927.151993
Thread_1 1606116928.1526074
Thread_2 1606116929.15364
Thread_2 1606116930.1542966
main thread out
Process finished with exit code 0