1:用this和类名.class却别对象时加锁的不同
用this
多线程调用同方法时 要调用的同一个第一对象的方法 不然打达不到线程加锁 因为他调用的是不同对象的锁
A a = new A();
Thread th1 = new Thread(a);
th1.start();
Thread th2 = new Thread(a);
th2.start();
Thread th3 = new Thread(a);
th3.start();
Thread th4 = new Thread(a);
th4.start();
public void run() {
while(flag){
synchronized (this) {
if(count<TATOL){
salticket();
}else{
flag = false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
用类名.class
不管实例化多少个对象 是对类对象进行加锁(反射)所以可以实例化多个对象 但仍可实现对同方法的加锁
Thread th1 = new Thread( new A());
th1.start();
Thread th2 = new Thread( new A());
th2.start();
Thread th3 = new Thread( new A());
th3.start();
public void run() {
while(flag){
synchronized (A.class) {
if(count<TATOL){
salticket();
}else{
flag = false;
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}