Thread类

import threading,time
count = 0
class MyThread(threading.Thread):
      def __init__(self,threadName):
          super(MyThread,self).__init__(name = threadName)
          
      def run(self):
          global count
          for i in range(10):
              count = count + 1
              time.sleep(0.3)  
              print(self.getName() , count)
    
for i in range(2):
    MyThread("MythreadName:"+str(i)).start()

运行结果

python常用类库——threading 

1.run方法

 在线程启动后执行预先写入的代码

2.start方法

启动线程 

Lock类

我们发现在打印的时候不像我们预期的那样顺序打印 会出现打印数字混乱 这是因为线程在同时运作的时候是不会关注其他线程的情况

因此需要lock去管理线程的进行

import threading
lock = threading.Lock()
lock.acquire()
lock.release()

一个线程对资源进行加锁操作之后其它线程就必须等它释放锁之后才能对该资源进行操作。acquire()与acquire_lock()都是加锁操作,release()与release_lock()都是释放锁操作,locked()与locked_lock()都是查询当前锁的状态。 

import threading,time

count = 0
class MyThread(threading.Thread):
    
      def __init__(self,threadName):
          super(MyThread,self).__init__(name = threadName)
          self.lock = lock
          
      def run(self):
          global count
          self.lock.acquire()
          for i in range(10):
              count = count + 1
              time.sleep(0.3)  
              print(self.getName() , count)
          self.lock.release()

lock = threading.Lock() #在程序开头,创建一个锁  
for i in range(2):
    MyThread("MythreadName:"+str(i)).start()

结果可以看到打印的和我们预期的一样两个线程协调的完成了任务

python常用类库——threading 

join类

join类的作用是将当前主线程堵塞的类,阻止全部线程继续运行,直至被调用的线程执行完毕

import threading,time
def doWaiting():
    print('start waiting:',time.strftime('%S'))
    time.sleep(3)
    print('stop waiting',time.strftime('%S'))
thread1 = threading.Thread(target = doWaiting)
thread1.start()
time.sleep(1)
print('start join')
thread1.join()
print('end join')

运行结果:

python常用类库——threading 

time设定了当前时间 当join启动后堵塞了整体进程的主进程 等待堵塞进程完成后才可以继续

相关文章: