线程安全学习笔记(一)
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();}}