java執行緒 存取錢問題
阿新 • • 發佈:2019-02-07
package com.qf.demo; /** * 有一張銀行卡 那朋友存錢 女朋友取錢 多執行緒 並且實現同步操作 * * 資源共享 有兩種操作 */ public class Thread4 { public static void main(String[] args) { Card card = new Card(); BoyFriend boyFriend = new BoyFriend(card); GirlFriend girlFriend = new GirlFriend(card); // Thread t = new Thread(boyFriend, "男朋友"); Thread t2 = new Thread(girlFriend, "女朋友"); t.start(); t2.start(); } } /** * 共享資源類 */ class Card { private int money; public int getMoney() { return money; } public void setMoney(int money) { this.money = money; } } /** * 存錢類 */ class BoyFriend implements Runnable{ // 將資源共享類作為操作類的屬性 Card card; public Card getCard() { return card; } public BoyFriend(Card card) { super(); this.card = card; } public void setCard(Card card) { this.card = card; } @Override public void run() { for (int i = 0; i < 10; i++) { synchronized(card){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } card.setMoney(card.getMoney()+1000); System.out.println(Thread.currentThread().getName()+"存了1000,還剩"+card.getMoney()); } } } } class GirlFriend implements Runnable{ Card card; public Card getCard() { return card; } public GirlFriend(Card card) { super(); this.card = card; } public void setCard(Card card) { this.card = card; } @Override public void run() { for (int i = 0; i < 10; i++) { synchronized(card){ if(card.getMoney()>=1000){ try { Thread.sleep(100); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } card.setMoney(card.getMoney()-1000); System.out.println(Thread.currentThread().getName()+"取了1000.,還剩"+card.getMoney()); }else { System.out.println("餘額不足"); } } } } }