import timeimport randomfrom threading import Thread, current_threaddeftask(name):print('%s is running on %s'% (name, current_thread().getName())) time.sleep(random.randint(1, 3))print('%s is done'% name)classMyThread(Thread):def__init__(self,name):super(MyThread, self).__init__() self.name = namedefrun(self):print('%s is running'% self.name) time.sleep(random.randint(1, 3))print('%s is done'% self.name)if__name__=='__main__': t1 =Thread(target=task, args=('Linda', )) t1.start() t2 =MyThread('Cathrine') t2.start()print('主...')
args中数据传递会共享
Lock解决数据共享错乱问题
子线程属性和方法
from threading import Thread, current_thread(), enumerate()
current_thread().getName()
t.getName()
t.setName('线程1')
t.isAlive()
t.deamon = True
t.join()
线程互斥锁
互斥锁原理:把并行变为串行,牺牲效率,保证数据安全,精髓在于把共享的部分数据加锁
from threading import Thread, Lockn =100deftask():global n mutex.acquire() temp = n time.sleep(0.1) n = temp -1 mutex.release()if__name__=='__main__': thread_li = [] mutex =Lock()for i inrange(100): t =Thread(target=task) thread_li.append(t) t.start()for t in thread_li: t.join()print(n)print('主...')