参考URL:Java并发性和多线程介绍
1.有四种不同的同步块:实例方法、静态方法、实例方法中的同步块、静态方法中的同步块
2.实例方法和静态方法同步语句的监视器对象不同。
// 实例方法
synchronized(this){
// 监视器this为实例对象
}
// 静态方法
synchronized(MyClass.class){
// 监视器MyClass.class为类对象,一个类只有一个类对象
}
3.Java同步实例:
在下面例子中,启动了两个线程,都调用Counter类同一个实例的add方法,只能有一个线程访问该方法。
public class Counter{
long count = 0;
public synchronized void add(long value){// run方法同步在实例上
this.count += value;
}
}
public class CounterThread extends Thread{
protected Counter counter = null;
public CounterThread(Counter counter){
this.counter = 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();
// CounterThread的构造器引用同一个Counter实例
Thread threadA = new CounterThread(counter);
Thread threadB = new CounterThread(counter);
// run方法同步在实例上,一个实例只能有一个线程
threadA.start();
threadB.start();
}
}
如果调用Counter类不同实例的add方法,就不存在同步的问题,它们可以同时执行。