本帖最后由 ld5128702 于 2013-4-12 00:43 编辑
- class Bank
- {
- private int sum;
- Object obj=new Object();
- public void add(int n)
- {
- //Object obj=new Object();刚才把这个给放在这里了,结果没起到作用,求高手给解释一下和上面正确位置的区别
- synchronized(obj)
- {
- sum=sum+n;
- System.out.println("sum:"+sum);
- }
-
- }
- }
- class Cus implements Runnable
- {
- private Bank b=new Bank();
- public void run()
- {
- for(int i=0;i<3;i++)
- {
- b.add(100);
-
- }
-
- }
- }
- class Demo02
- {
- public static void main(String args[])
- {
- Cus c=new Cus();
- Thread t1=new Thread(c);
- Thread t2=new Thread(c);
- t1.start();
- t2.start();
- }
- }
复制代码 |