本帖最后由 匡文 于 2013-10-21 17:44 编辑
是毕老师视频中讲解线程的一个例子,我按着他的思路敲的代码,同步的语句加了锁(obj),但是仍然没能同步- class Bank{
- private int sum;
- public void add(int i){
- Object obj = new Object();
- synchronized (obj){
- sum = sum + i;
- try{
- Thread.sleep(100);
- }catch(Exception e){
- }
- System.out.println(Thread.currentThread().getName()+"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 TestBank{
- public static void main(String[] args){
- Cus c = new Cus();
-
- Thread t1 = new Thread(c);
- Thread t2 = new Thread(c);
- t1.start();
- t2.start();
- }
- }
复制代码 按理说加了锁之后,无论运行多少次,输出结果都应该是
Thread-0sum= 100 Thread-1sum= 200 Thread-0sum= 400 Thread-1sum= 500 Thread-0sum= 600 Thread-1sum= 600
但是,上面代码输出结果偶尔仍然是:
Thread-0sum= 200 Thread-1sum= 200 Thread-0sum= 400 Thread-1sum= 500 Thread-0sum= 600 Thread-1sum= 600
“200”出现了2次,“100”没有出现,说明还是存在线程安全问题。。。但是我已经加锁了的呀,这是为什么?
|