python高级编程之多线程threading
官方文档
threading线程教程
官方文档
简单线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from threading import Thread
def my_thread(data='default'): for i in range(5): print(data) time.sleep(1)
if __name__ == '__main__': thread_01 = Thread(target=my_thread, name='thread_01') thread_02 = Thread(target=my_thread, name='thread_02', args=('undefault',)) print('1.strat...') thread_01.start() print('2.strat...') thread_02.start() thread_01.join() thread_02.join() print('ending......')
|
线程加锁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| from threading import Thread, Lock
lock = Lock()
def my_thread(data='default'): for i in range(5): lock.acquire() print(data) lock.release() time.sleep(1)
if __name__ == '__main__': thread_01 = Thread(target=my_thread, name='thread_01') thread_02 = Thread(target=my_thread, name='thread_02', args=('undefault',)) print('1.strat...') thread_01.start() print('2.strat...') thread_02.start() thread_01.join() thread_02.join() print('ending......')
|
类线程继承,实现多线程
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| from threading import Thread, Lock
lock = Lock()
def my_thread(data='default'): for i in range(5): lock.acquire() print(data) lock.release() time.sleep(1)
class MyThread(Thread): def __init__(self, data='default'): super().__init__() self.name = name
def run(self): print(self.ident) my_thread(self.name)
if __name__ == '__main__': thread_03 = MyThread() thread_04 = MyThread(data='undefault') thread_03.start() thread_04.start() thread_03.join() thread_04.join() print('ending......')
|
向博主反馈问题