首页 新闻 会员 周边 捐助

java的同步问题,帮忙看下

0
[已关闭问题] 关闭于 2016-11-09 20:03
大家帮忙看下,为什么运行结果不是100,总是变来变去,求指点。

1
public class ThreadTest 2 { 3 public static void main(String[] args) 4 { 5 Example example = new Example(); 6 7 ExecutorService es = Executors.newCachedThreadPool(); 8 for (int i = 0; i < 10; i++) { 9 es.execute(new Thread1(example)); 10 es.execute(new Thread2(example)); 11 } 12 es.shutdown(); 13 14 System.out.println(example.i); 15 } 16 17 } 18 19 class Example 20 { 21 private Object object = new Object(); 22 23 int i = 100; 24 25 public void execute() 26 { 27 synchronized (object) 28 { 29 i++; 30 } 31 } 32 33 public void execute2() 34 { 35 synchronized (object) 36 { 37 i--; 38 } 39 } 40 41 } 42 43 class Thread1 implements Runnable 44 { 45 private Example example; 46 47 public Thread1(Example example) 48 { 49 this.example = example; 50 } 51 52 @Override 53 public void run() 54 { 55 example.execute(); 56 } 57 58 } 59 60 class Thread2 implements Runnable 61 { 62 private Example example; 63 64 public Thread2(Example example) 65 { 66 this.example = example; 67 } 68 69 @Override 70 public void run() 71 { 72 example.execute2(); 73 } 74 75 }
孩子爹的主页 孩子爹 | 菜鸟二级 | 园豆:204
提问于:2016-11-09 19:22
< >
分享
所有回答(1)
0
 1 public static void main(String[] args) throws InterruptedException {
 2         Example example = new Example();
 3 
 4         ExecutorService es = Executors.newCachedThreadPool();
 5         for (int i = 0; i < 10; i++) {
 6             es.execute(new Thread1(example));
 7             es.execute(new Thread2(example));
 8 
 9             // new Thread(new Thread1(example)).start();
10             // new Thread(new Thread2(example)).start();
11         }
12         Thread.sleep(200); // 休息200毫秒
13         System.out.println(example.i);
14         es.shutdown();
15     }

 

孩子爹 | 园豆:204 (菜鸟二级) | 2016-11-09 20:03
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册