synchronized代码块为一段代码加锁。
在Thread多线程的实现内synchronized的锁对象需要时各个线程都可以访问得到的对象,如类的static变量。如果synchronized使用的锁是对象自己所拥有的,则起不到互斥的效果。
private static int index=0;
private String string = new String("dfd");//无法达到互斥的效果
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(string){
for(int i=0 ;i<100;i++){
System.out.println(getName()+" "+index++);
}
}}
Thread thread1 = new TestSync();
Thread thread2 = new TestSync();
Thread thread3 = new TestSync();
thread1.start();
thread2.start();
thread3.start();