同步静态方法
修饰静态方法,作用于当前类对象加锁,进入同步代码前要获得当前类对象的锁
同步监视器是当前类对象Class c=Date.class
public class App {
private static int num = 0;
public static synchronized void add() {
System.out.println(Thread.currentThread().getName()+":begin...."+new Date());
int cc = num;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
cc++;
num = cc;
System.out.println(cc);
System.out.println(Thread.currentThread().getName()+":end...."+new Date());
}
public static void main(String[] args)throws Exception {
Thread[] ts=new Thread[10];
for(int i=0;i<ts.length;i++) {
Runnable r=new Runnable() {
public void run() {
App app=new App();
app.add();
}
};
ts[i]=new Thread(r);
ts[i].start();
}
for(Thread temp:ts) {
temp.join();
}
System.out.println("Main:"+num);
}
}
注意:如果在方法上去掉static,则不能实现锁定效果,因为是对象锁,而在线程中创建了10个对象,各个对象没有任何关系,所以不能达到锁定的效果,但是类锁的效果仍旧有效