synchronized的两种用法(本质锁的)都是对象
示例代码:
public class TestSychronized {
public static void main(String[] args) {
new Thread(new TH()).start();
new Thread(new TH()).start();
}
}
class TH implements Runnable{
private static Cat cat=new Cat();
@Override
public void run() {
cat.test();
}
}
class Cat{
//第一种,所的是调用此方法的对象
public synchronized void test(){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("11111");
}
//第二种,锁的直接是括号里面的对象
public void test(){
synchronized(Object.class//this(this依然指的是调用此方法的对象本身)){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("11111");
}
}
}
914

被折叠的 条评论
为什么被折叠?



