标签:定义 同步 nts 两种 while start 分析 ack star
package com.qf.work; /** * 张三和妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存取款的操作,请使用多线程及同步方法模拟张三和妻子同时取款的过程。 要求使用同步方法和同步代码块两种方式实现 分析 定义Account类表示银行帐户 定义两个线程分别实现张三和妻子取款的操作 */ public class Work4 { public static void main(String[] args) { Account account = new Account(); SaveMoney saveMoney = new SaveMoney(account); TakeMoney takeMoney = new TakeMoney(account); Thread t0 = new Thread(saveMoney); Thread t1 = new Thread(takeMoney); t0.start(); t1.start(); } } class Account{ int sum = 100; public synchronized void saveMoney() { sum += 10; System.out.println(Thread.currentThread().getName() +" 存款后:"+ sum); } public synchronized void takeMoney() { if(sum > 0) { sum -= 1; System.out.println(Thread.currentThread().getName() +"取款后"+ sum); } } } class SaveMoney implements Runnable{ Account account; int i = 1; public SaveMoney(Account account) { this.account = account; } @Override public void run() { synchronized (this) { while(i <= 100) { account.saveMoney(); i++; } } } } class TakeMoney implements Runnable{ Account account; int i = 1; public TakeMoney(Account account) { this.account = account; } @Override public void run() { synchronized (this) { while(i <= 100) { account.takeMoney(); i++; } } } }
标签:定义 同步 nts 两种 while start 分析 ack star
原文地址:https://www.cnblogs.com/yumengfei/p/11005901.html