java 同步方法_java的同步方法

同步方法锁的是对象

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();

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值