标签:final port zha nts java7 exception color except 信号
1.新建Account类,使用Semaphore同步增加和减少金额方法。
package com.xkzhangsan.semaphorepack.bank; import java.util.concurrent.Semaphore; public class Account { private double balance; private final Semaphore semaphore = new Semaphore(1); public void addAmount(double amount){ try { semaphore.acquire(); double tmp = balance; Thread.sleep(10); tmp+=amount; balance=tmp; } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } public void substractAmount(double amount){ try { semaphore.acquire(); double tmp = balance; Thread.sleep(10); tmp-=amount; balance=tmp; } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); } } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } }
2.其他和https://www.cnblogs.com/xkzhangsanx/p/10759690.html一致。
注意释放信号量
} finally {
semaphore.release();
}
3.测试结果
Account start money:1000.000000 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Company add 1000 balance:2000.0 Bank substract 1000 balance:1000.0 Account end money:1000.000000
参考:java7并发编程实战手册
GitHub地址:https://github.com/xkzhangsan/java-concurrent-practice
标签:final port zha nts java7 exception color except 信号
原文地址:https://www.cnblogs.com/xkzhangsanx/p/10771760.html