本帖最后由 hejinzhong 于 2014-7-20 15:30 编辑
- <p> class Bank
- {
- private int sum=0;</p><p> public void add(int n)
- {
- sum = sum + n;
-
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- }
- System.out.println("sum="+sum);
- }
- }</p><p>class Cus implements Runnable
- {
- private Bank b = new Bank();
- public void run()
- {
- Object obj = new Object();
- for(int i=0;i<3;i++)
- {
- synchronized(obj)
- {
- b.add(100);// 这里有锁,不是函数add执行完,其他才能进来吗,为什么结果不对?
- }
- }
- }
- }</p><p>class SynchronizedDemo
- {
- public static void main(String[] args)
- {
- Cus c = new Cus();
- Thread t0 = new Thread(c);
- Thread t1 = new Thread(c);
- t0.start();
- t1.start();
- }
- }</p>
复制代码
|
|