1,创建需要同步的对象(方式一)
package concurrency; public class Bank { private double amount; public Bank(double amount){ this.amount = amount; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public synchronized void addAmount(double money){ System.out.println("当前金额为: "+amount); amount = amount + money; System.out.println("增加"+money+"后的金额为:"+amount); } public synchronized void substract(double money){ System.out.println("当前金额为: "+amount); amount = amount - money; System.out.println("减少"+money+"后的金额为:"+amount); } }
2,创建两个线程对象
package concurrency; public class AddMoneyThread implements Runnable{ private Bank bank; private double money; public AddMoneyThread(Bank bank,double money){ this.bank = bank; this.money = money; } /** * @see java.lang.Runnable#run() */ @Override public void run() { for(int i=0;i<10;i++){ bank.addAmount(money); } } }
package concurrency; public class SubstractMoneyThread implements Runnable{ private Bank bank; private double money; public SubstractMoneyThread(Bank bank,double money){ this.bank = bank; this.money = money; } /** * @see java.lang.Runnable#run() */ @Override public void run() { for(int i=0;i<10;i++){ bank.substract(money); } } }
3,创建测试类
package concurrency; public class ConcurrencyTest { public static void main(String[] args) { Bank bank = new Bank(1000); AddMoneyThread addThread = new AddMoneyThread(bank, 10); SubstractMoneyThread subThread = new SubstractMoneyThread(bank, 10); Thread addT = new Thread(addThread); Thread subT = new Thread(subThread); addT.start(); subT.start(); } }
4,创建需要同步的对象(方式二)
package concurrency; public class Bank { private double amount; public Bank(double amount){ this.amount = amount; } public double getAmount() { return amount; } public void setAmount(double amount) { this.amount = amount; } public void addAmount(double money){ synchronized(this){ System.out.println("当前金额为: "+amount); amount = amount + money; System.out.println("增加"+money+"后的金额为:"+amount); } } public void substract(double money){ synchronized(this){ System.out.println("当前金额为: "+amount); amount = amount - money; System.out.println("减少"+money+"后的金额为:"+amount); } } }
1,synchronized作为一种同步手段,解决java多线程的执行有序性和内 存可见性
2,一个线程执行临界区代码过程如下:
(1) 获得同步锁
(2)清空工作内存
(3) 从主存拷贝变量副本到工作内存
(4) 对这些变量计算
(5) 将变量从工作内存写回到主存
(6) 释放锁
有几个问题不是很清楚。
我给方法上或者同步对象上加了锁,但是发现synchronized所包围的块是一个原子操作?不知道是什么原因?
个人的理解是:同步对象被加了锁,同步对象只能被一个线程访问。
该对象中的方法也只能被一个线程访问????
求指点!