synchronized的使用,是线程并行访问数据的时候常用的一种保证数据一致性的方式,在同步代码段访问期间,其他线程不能对其进行访问。
synchronized修饰的方法在访问期间,非synchronized修饰的方法可以访问么?
(之前不清楚,现在知道了其实很好去想,因为synchronized修改的方法其实等同于synchorinized(this),而没有同步的代码当然是可以访问的。)--这种想法其实也不严谨,就是不能访问也没可以呀,所以还是记住吧,有空深入研究下再下定论,现在还是记住结果吧。
为了记忆深刻,自己写个程序验证一下见代码1。
执行结果可以看出来,noSynFun没有等待synFun执行完成就开始执行了而synFun2等到synFun执行完成后执行。
synchronized修饰的函数只相当于修饰了synchronized(this),不能保证其成员数据的一致性,除非成员的访问全部控制在改对象内,且都使用同步锁修饰。但很容易出现疏忽,比如下面的代码2,表面上看都是用同步锁修饰了,但是暴露了成员对象b本身,就能对成员B进行add与remove操作而跳过了对象A中的add与remove。
代码1
package synchronize;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
public class SynchronizedDemo extends Thread {
private CountDownLatch myL = null;
public SynchronizedDemo(CountDownLatch latch) {
// TODO Auto-generated constructor stub
myL = latch;
}
public void run()
{
try {
synFun();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private synchronized void synFun() throws InterruptedException
{
myL.countDown();
System.out.println(" synFun wait 5s,current time is "+new Date());
Thread.currentThread().sleep(5000);
System.out.println("synFun return");
}
private void noSynFun()
{
System.out.println("I'm in noSynFun ,runtime is "+ new Date());
}
private synchronized void synFun2()
{
System.out.println("I'm in SynFun2 ,runtime is "+ new Date());
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//在synFun开始执行的时候countDown,保证执行了synFun中,尝试执行noSynFun
CountDownLatch latch = new CountDownLatch(1);
SynchronizedDemo demo = new SynchronizedDemo(latch);
demo.start();
try {
latch.await();//保证已经开始执行synFun
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
demo.noSynFun();
demo.synFun2();
}
}
执行结果:
synFun wait 5s,current time is Thu Jan 23 23:05:43 CST 2014
I'm in noSynFun ,runtime is Thu Jan 23 23:05:43 CST 2014
synFun return
I'm in SynFun2 ,runtime is Thu Jan 23 23:05:48 CST 2014
代码2
package synchronize;
import java.util.Vector;
public class Demo2 extends Thread {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Demo2 a = new Demo2();
Vector b = a.getB();//越过了同步,随便访问了。
b.add(new Object());
}
Vector memberB = new Vector();
public synchronized void add(Object o)
{
memberB.add(o);
}
public synchronized void remove(Object o)
{
memberB.remove(o);
}
//暴露出来了,就不可控了
public synchronized Vector getB()
{
return memberB;
}
}