synchronized修饰静态方法作用于类,锁是当前class对象,通过这个类生成的线程,走到被synchronized修饰的方法时,都需要等待获取锁后才能执行。
public class Synchronized2 implements Runnable{
static int n = 0;
public static synchronized void add() {
n++;
}
@Override
public void run() {
for (int i = 0; i < 100000; i++) {
add();
}
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Synchronized2());
Thread t2 = new Thread(new Synchronized2());
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(n);
}
}
控制台输出
200000