码迷,mamicode.com
首页 > 编程语言 > 详细

java并发编程(一)

时间:2014-12-08 22:42:42      阅读:285      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   使用   sp   for   

多个线程访问同一个变量时,可能会出现问题。这里我用两个线程同时访问一个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 }

bubuko.com,布布扣

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

 

java并发编程(一)

标签:style   blog   http   io   ar   color   使用   sp   for   

原文地址:http://www.cnblogs.com/luckygxf/p/4152063.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!