本帖最后由 山里孩子 于 2015-3-23 23:42 编辑
在这个代码中,正常输出是:
sum=100
sum=200
sum=300
sum=400
sum=500
sum=600
不知道哪里问题怎么输出是这个样子:
sum=200
sum=200
sum=400
sum=400
sum=600
sum=600
- class Bank
- {
- private int sum ;
- public void add(int number)
- {
- Object obj = new Object();
- synchronized(obj)
- {
- sum = sum + number;
- try
- {
- Thread.sleep(10);
- }
- catch (Exception e)
- {
- }
- System.out.println("sum="+sum);
- }
- }
- }
- class User implements Runnable
- {
- Bank bank = new Bank();
- public void run()
- {
- for ( int i=0 ; i<3 ; i++ )
- {
- bank.add(100);
- }
- }
- }
- class ThreadDemo3
- {
- public static void main(String[] args)
- {
- User u = new User();
- Thread u1 = new Thread(u);
- Thread u2 = new Thread(u);
- u1.start();
- u2.start();
- }
- }
复制代码
|
|