java并发编程(一)

多个线程访问同一个变量时,可能会出现问题。这里我用两个线程同时访问一个int count变量,让他们同时+1。同时让线程睡眠1秒,每个线程执行10次,最后应该输出20才对,因为count++并不是原子操作,这里需要做并发处理,如用syn...什么关键词,当然还有别的方法。后面在说

这里为了是两个线程访问的是同一个变量我使用了静态变量private static int count = 1

Thread1线程类

 1 package com.gxf.thread;
 2 
 3 public class Thread1 extends Thread {
 4     private static int count = 1;
 5 
 6     
 7     @Override
 8     public void run() {
 9         super.run();
10         for(int i = 0; i < 10; i++){
11             System.out.println("in thread count = " + count++);
12             try {
13                 sleep(1000);
14             } catch (InterruptedException e) {
15                 // TODO Auto-generated catch block
16                 e.printStackTrace();
17             }
18         }
19     }
20 
21 }

Test.java测试类

 1 package com.gxf.thread;
 2 
 3 public class Test {
 4 
 5     public static void main(String[] args) {
 6         Thread thread1 = new Thread1();
 7         
 8         Thread thread2 = new Thread1();
 9     
10         
11         thread1.start();
12         thread2.start();
13     }
14 
15 }

从上面可以看到出现了两个15,说明从14到15或者13到14中间出了问题,这就是线程安全问题

 

posted on 2014-12-08 22:04  luckygxf  阅读(174)  评论(0编辑  收藏  举报

导航