Python语言基础1.2

165 阅读1分钟

例子:取钱同步锁

1、新建People人类

class People:
   def __init__(self, name):
      self.name = name

2、新建Card卡类

import threading
import People

class Card:
   def __init__(self, account, password, balance, people):
      self.account = account
      self.password = password
      self.balance = balance
      self.people = people
      self.lock = threading.RLock()

   def setBalance(self, balance):
      if isinstance(balance, float):
         self.balance = balance
      else:
         print("数据类型错误!")

   def getBalance(self):
      return self.balance

   temp_people = People

   def getMoney(self, account_p, password_p, get_money, temp_people):
      self.lock.acquire()
      if "admin" == account_p and "123456" == password_p:
         try:
            if self.balance >= get_money:
               print(temp_people.name + "取钱:" + str(get_money) + "元")
               self.setBalance(self.balance - get_money)
               print("\n余额为: " + str(self.getBalance()))
            else:
               print(temp_people.name + "取钱失败,因为余额不足!")
         finally:
            self.lock.release()
      else:
         print("密码或账号错误!")

3、第一种通过面向过程执行多线程

import threading
import People

def getMoney_1(card, account_1, password_1, money_1, peple_1):
   card.getMoney(account_1, password_1, money_1, peple_1)

sam = People("山姆")
jim = People("杰姆")
new_card = Card("admin""123456"1000.00, sam)
threading.Thread(name=sam.name, target=getMoney_1, args=(new_card, "admin""123456"800.00, sam)).start()
threading.Thread(name=jim.name, target=getMoney_1, args=(new_card, "admin""123456"800.00, jim)).start()

4、第二种通过面向对象执行多线程

4.1)新建线程类

import th reading
import People

class MyThread(threading.Thread):
   def __init__(self, people, card, howMoney):
      threading.Thread.__init__(self)
      self.people = people
      self.card = card
      self.howMoney = howMoney

   def run(self):
      self.card.getMoney(self.card.account, self.card.password, self.howMoney, self.people)

4.2)通过循环执行多线程

import threading
import People
import MyThread

if __name__ == '__main__':
   sam = People("山姆")
   jim = People("杰姆")
   new_card = Card("admin""123456"1000.00, sam)
   th_sam = myThread(sam, new_card, 800.00)
   th_jim = myThread(jim, new_card, 800.00)

   threads = [th_sam, th_jim]

   for th in threads:
      th.start()
      print("退出主线程")

5、线程模块threading

5.1)RLock() 方法,同步锁

self.lock = threading.RLock()   #写在需要加锁的类的__init__方法中
self.lock.acquire()   #调用加同步锁
self.lock.release()   #释放同步锁

5.2)start()方法,启动线程

threading.Thread(name=test_1, target=test_2, args=("admin""123456")).start()
name=test_1:启动线程的名称
target=test_2:启动线程时调用的方法,test_2不是类的方法,一定时全局方法
args=("admin""123456"):test_2方法中需要传入的参数
start():确定线程