标记一个方法或代码块,防止调用冲突,被标记synchronized的代码 , 同一时该只能有一个线程操作它。

synchronized关键词可被用在4种情况下:

  • 实例方法
  • 静态方法
  • 实例化方法里
  • 静态方法里

Synchronized Instance Methods示例:

public synchronized void add(int value){
this.count += value;
}

Synchronized Static Methods示例:

public static synchronized void add(int value){
count += value;
}

Synchroinzed Blocks in Instance Methods示例(嵌在Unsynchronized java代码里):

public void add(int value){
synchronized(this){
this.count += value;
}
}

下面是在类的实例中使用Synchronized的示例

public class MyClass {

public synchronized void log1(String msg1, String msg2){
log.writeln(msg1);
log.writeln(msg2);
}
public void log2(String msg1, String msg2){
synchronized(this){
log.writeln(msg1);
log.writeln(msg2);
}
}
}

下面是调用的示例:

public class Counter{

long count = 0;

public synchronized void add(long value){
this.count += value;
}
}
public class CounterThread extends Thread{

protected Counter counter = null;

public CounterThread(Counter counter){
this.counter = counter;
}

public void run() {
for(int i=0; i<10; i++){
counter.add(i);
}
}
}
public class Example {

public static void main(String[] args){
Counter counter = new Counter();
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);

threadA.start();
threadB.start();
}
}

这里threadA与threadB是会发生阻塞的。

而下面的示例:

public class Example {

public static void main(String[] args){
Counter counterA = new Counter();
Counter counterB = new Counter();
Thread threadA = new CounterThread(counterA);
Thread threadB = new CounterThread(counterB);

threadA.start();
threadB.start();
}
}

这时ThreadA与ThreadB,不再引用相同的计数器实例,counterA与counterB则不会发生阻塞。