首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

线程保险学习笔记(一)

2012-08-27 
线程安全学习笔记(一)Java面试的话,基本肯定会问到的一个问题就是关于volatile与syncronized的区别. Syncr

线程安全学习笔记(一)
Java面试的话,基本肯定会问到的一个问题就是关于volatile与syncronized的区别. Syncronized强同步,volatile弱;volat不好用,想我这样的菜鸟用不来.这是我对于这两个的认识,其他更高深的就说不上来了.
先来看下syncronized的作用,这里以StringBuilder和StringBuffer为例来说明。
线程类实现:

package test;import java.util.Vector;import com.maximilian.www.MyTestThread;public class MyTest{private static int loopTimes=10;private static int threadNum = 2;private static int threadId;private static Vector<Thread> threads = new Vector<Thread>();public static void main (String [] args){    for(threadId=0;threadId < threadNum ;threadId++)    {    Thread t = new Thread(new MyTestThread(threadId, loopTimes),"mytestthread");    threads.add(t);    }    for(Thread t:threads)    {    t.start();    }    for(Thread t:threads)    {    try            {            t.join();            } catch (InterruptedException e)            {            // TODO Auto-generated catch block            e.printStackTrace();            }    }    System.out.println("+++++++++++++++++++++++++sb1++++++++++++++++++++++");    MyTestThread.printSb1();    System.out.println("+++++++++++++++++++++++++sb2++++++++++++++++++++++");    MyTestThread.printSb2();    System.out.println("+++++++++++++++++++++++++sb3++++++++++++++++++++++");    MyTestThread.printSb3();}}


上面的代码主要是实现字符串的连接。先看结果如何:
+++++++++++++++++++++++++sb1++++++++++++++++++++++
thread0:10
thread0:9
thread1:10
thread0:8
thread1:9
thread0:7
thread1:8
thread0:6
thread1:7
thread0:5
thread1:6
thread0:4
thread1:5
thread0:thread31
:4
thread1thread:03:
2
thread1:2
thread0:thread11
:1
+++++++++++++++++++++++++sb2++++++++++++++++++++++
thread0:10
thread0:9
thread1:10
thread0:8
thread1:9
thread0:7
thread1:8
thread0:6
thread1:7
thread0:5
thread1:6
thread0:4
thread1:5t
read
0:3
thread1:4hread 0:1
thread1:2
thread1:1
+++++++++++++++++++++++++sb3++++++++++++++++++++++
thread0:10
thread0:9
thread1:10
thread0:8
thread1:9
thread0:7
thread1:8
thread0:6
thread1:7
thread0:5
thread1:6
thread0:4
thread1:5
thread1:4
thread0:3
thread1:3
thread0:2
thread1:2
thread1:1
thread0:1

看一下StringBuilder和StringBuffer的代码可以发现,他们的代码除了StringBuffer在方法前面加了syncronized其他完全一样,这也是导致sb2会出现即使是在一个append中的内容都会有其他的加入的情况(红色部分),而sb1出现红色部分的情况是因为虽然append这个方法是线程安全,但是append操作之间是没有同步的,这个在要求线程一次完全连接操作时可以用sb3的方法,或者个人认为更好的对整个连接过程加syncronized。
    另外,注意join的调用不能跟start一起遍历时操作,不然会导致线程是一个个顺序线性执行。

热点排行