并不是在钻牛角尖,是对程序的调用和多线程不理解,希望大神指教
- //--为什么我在sum += n;上面进行try也会发生输出错误,
- //--不是应该在sum += n 和输出语句之间try 才会发生异常的么??
- class Bank
- {
- private int sum;
- public void add(int n)
- {
- try{Thread.sleep(200);}catch(Exception e){}
- sum += n;
- System.out.println("sum = "+sum);
- }
- }
- class Cus implements Runnable
- {
- private Bank b = new Bank();
- public void run()
- {
-
- for(int x=0;x<3;x++)
- {
- b.add(100);
- }
- }
- }
- class RunnableDemo
- {
- 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 = 300
sum = 400
sum = 500
*/ |
|