`
wajsjh0813
  • 浏览: 5494 次
  • 性别: Icon_minigender_1
  • 来自: 南京
最近访客 更多访客>>
社区版块
存档分类
最新评论

java线程同步的理解

 
阅读更多
假如二个人拥有同一个银行账户,同时到银行取钱;二个人是二个线程,人与银行账户的关系式聚集的关系。
public class Demo5 implements Runnable {

Account1 a = null;
public static void main(String[] args) {
// TODO Auto-generated method stub
Account1 a1 = new Account1();
Demo5 d1 = new Demo5();
Demo5 d2 = new Demo5();
d1.setA(a1);
d2.setA(a1);
Thread t1 = new Thread(d1);
Thread t2 = new Thread(d2);
t1.start();
t2.start();
}

public void run() {
// TODO Auto-generated method stub
a.takeOutmoney(10);
}

public Account1 getA() {
return a;
}

public void setA(Account1 a) {
this.a = a;
}
}
class Account1{
static int sum = 100;
public void takeOutmoney(int mon){
synchronized (this){
sum-=mon;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Account1.sum);
}
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics