class Bank
{
private int sum;
Object obj = new Object();
public synchronized void add(int n)
{
//synchronized(obj)
//{
sum = sum + n;
try
{
Thread.sleep(10);
System.out.println("sum =" + sum);
}
catch(Exception e)
{
}
//}
}
}
class Cus implements Runnable
{
public void run()
{
Bank b = new Bank();
for(int x = 0 ; x < 3 ; x++)
{
b.add(100);
}
}
}
public class BankDemo
{
public static void main(String[] args)
{
Cus c = new Cus();
Thread t1 = new Thread(c);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
我运行的结果是:
sum =100
sum =100
sum =200
sum =200
sum =300
sum =300
疑问:为什么结果不是像毕老师里面的那样?
sum =100
sum =200
sum =300
sum =400
sum =500
sum =600