多线程:三大不安全案例
生活随笔
收集整理的這篇文章主要介紹了
多线程:三大不安全案例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package com.wuming.syn;
//不安全的取錢
//兩個人去銀行取錢,賬戶
public class UnSafeBank {public static void main(String[] args) {//賬戶Account account = new Account(100,"結婚基金");Drawing you = new Drawing(account,50,"你");Drawing girlFriend = new Drawing(account,100,"girlFriend");you.start();girlFriend.start();}}
//賬戶
class Account{int money;//余額String name;//卡名public Account(int money, String name) {this.money = money;this.name = name;}
}//銀行,模擬取款
class Drawing extends Thread{Account account;//賬戶//取了多少錢int drawingMoney;//現在手里有多少錢int nowMoney;public Drawing(Account account, int drawingMoney, String name) {super(name);//線程namethis.account = account;this.drawingMoney = drawingMoney;this.nowMoney = nowMoney;}
//取錢@Overridepublic void run() {//判斷有沒有錢if(account.money-drawingMoney<0){System.out.println(Thread.currentThread().getName()+"錢不夠,取不了");return;}//卡內余額=余額-你取的錢account.money=account.money-drawingMoney;//你手里的錢nowMoney=nowMoney+drawingMoney;System.out.println(account.name+"余額為:"+account.money);//Thread.currentThread().getName()=this.getName();System.out.println(this.getName()+"手里的錢"+nowMoney);}
}
結婚基金余額為:50
你手里的錢50
girlFriend錢不夠,取不了
=================
模擬延時
package com.wuming.syn; //不安全的取錢 //兩個人去銀行取錢,賬戶 public class UnSafeBank {public static void main(String[] args) {//賬戶Account account = new Account(100,"結婚基金");Drawing you = new Drawing(account,50,"你");Drawing girlFriend = new Drawing(account,100,"girlFriend");you.start();girlFriend.start();}} //賬戶 class Account{int money;//余額String name;//卡名public Account(int money, String name) {this.money = money;this.name = name;} }//銀行,模擬取款 class Drawing extends Thread{Account account;//賬戶//取了多少錢int drawingMoney;//現在手里有多少錢int nowMoney;public Drawing(Account account, int drawingMoney, String name) {super(name);//線程namethis.account = account;this.drawingMoney = drawingMoney;this.nowMoney = nowMoney;} //取錢@Overridepublic void run() {//判斷有沒有錢if(account.money-drawingMoney<0){System.out.println(Thread.currentThread().getName()+"錢不夠,取不了");return;}//sleep可以放大問題的發生性try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}//卡內余額=余額-你取的錢account.money=account.money-drawingMoney;//你手里的錢nowMoney=nowMoney+drawingMoney;System.out.println(account.name+"余額為:"+account.money);//Thread.currentThread().getName()=this.getName();System.out.println(this.getName()+"手里的錢"+nowMoney);} }結婚基金余額為:0
girlFriend手里的錢100
結婚基金余額為:-50
你手里的錢50
總結
以上是生活随笔為你收集整理的多线程:三大不安全案例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: BugkuCTF-WEB题前女友
- 下一篇: C语言 memcpy 和 strcpy