同步方法锁的是对象
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
当一个线程正在执行某个对象的同步方法的时候,其所有要执行这个对象的任意一个同步方法的其他线程都得等待,直到对象锁被释放。
在下面的例子中,只有线程1和线程3能够得到执行机会,因为线程2调用的也是一个同步方法value2(), 而线程1调用的value1()永远不返回(就不释放对象counter的锁).
public class Counter {
private int counter;
public synchronized void value1(){
counter = 1;
while(true){
String threadName = Thread.currentThread().getName();
System.out.println("我是一个线程,我的名字是 " + threadName + "我调用的是value1()");
System.out.println("一旦我获得对象" + this + "的内部锁,其他线程都无法执行了");
System.out.println("我只是想说明synchornized 方法锁的是对象,用的是对象的内部锁intrinsic locks");
}
}
/**
public void value3(){
synchronized(this){
counter = 1;
while(true){
String threadName = Thread.currentThread().getName();
System.out.println("我是一个线程,我的名字是 " + threadName);
System.out.println("一旦我获得对象" + this + "的内部锁,其他线程都无法执行了");
System.out.println("我只是想说明synchornized 方法锁的是对象,用的是对象的内部锁intrinsic locks");
}
}
}
**/
public synchronized void value2(){
counter = 2;
while(true){
String threadName = Thread.currentThread().getName();
System.out.println("我是一个线程,我的名字是 " + threadName + "我调用的是value2()");
System.out.println("一旦我获得对象" + this + "的内部锁,其他线程都无法执行了");
System.out.println("我只是想说明synchornized 方法锁的是对象,用的是对象的内部锁intrinsic locks");
}
}
public void value(){
while(true){
String threadName = Thread.currentThread().getName();
System.out.println("我是一个线程,我的名字是 " + threadName);
System.out.println("我调用的是对象" + this + "的不加synchronzied方法value(), 我不独占这个对象,其他线程可以调用,其实我人很好" );
}
}
public static void main(String... args){
Counter ctr = new Counter();
new Thread1(ctr).start();
new Thread2(ctr).start();
new Thread3(ctr).start();
}
private static class Thread1 extends Thread{
private Counter counter;
public Thread1(Counter counter){
this.counter = counter;
this.setName(" 线程 1 ");
}
public void run(){
counter.value1();
}
}
private static class Thread2 extends Thread{
private Counter counter;
public Thread2(Counter counter){
this.counter = counter;
this.setName(" 线程 2 ");
}
public void run(){
counter.value2();
}
}
private static class Thread3 extends Thread{
private Counter counter;
public Thread3(Counter counter){
this.counter = counter;
this.setName(" 线程 3 ");
}
public void run(){
counter.value();
}
}
}