1.主线程
import threading
t = threading.current_thread()
print(t) # <_MainThread(MainThread, started 139908235814720)>
print(t.getName()) # MainThread
print(t.ident) # 139908235814720
print(t.isAlive()) # True
2.创建线程
my_thread = threading.Thread()
my_thread = threading.Thread(name='my_thread')
def print_i(i):
print('打印i:%d'%(i,))
my_thread = threading.Thread(target=print_i,args=(1,))
my_thread().start()
3 交替获得CPU时间片
import time
from datetime import datetime
import threading
def print_time():
for _ in range(5): # 在每个线程中打印5次
time.sleep(0.1) # 模拟打印前的相关处理逻辑
print('当前线程%s,打印结束时间为:%s'%(threading.current_thread().getName(),datetime.today()))
threads = [threading.Thread(name='t%d'%(i,),target=print_time) for i in range(3)]
[t.start() for t in threads]
4.多线程抢夺同一个变量,要加锁
import threading
import time
locka = threading.Lock()
a = 0
def add1():
global a
try:
locka.acquire() # 获得锁
tmp = a + 1
time.sleep(0.2) # 延时0.2秒,模拟写入所需时间
a = tmp
finally:
locka.release() # 释放锁
print('%s adds a to 1: %d'%(threading.current_thread().getName(),a))
threads = [threading.Thread(name='t%d'%(i,),target=add1) for i in range(10)]
[t.start() for t in threads]