java两个对象调用一个方法_java - 如果我在同一个类上同步两个方法,它们可以同时运行吗?...

同步的关键思想不容易陷入,只有在相同的对象实例上调用方法时它才有效 - 它已在答案和注释中突出显示 -

下面的示例程序是明确指出相同的 -

public class Test {

public synchronized void methodA(String currentObjectName) throws InterruptedException {

System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA in");

Thread.sleep(1000);

System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodA out");

}

public synchronized void methodB(String currentObjectName) throws InterruptedException {

System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB in");

Thread.sleep(1000);

System.out.println(Thread.currentThread().getName() + "->" +currentObjectName + "->methodB out");

}

public static void main(String[] args){

Test object1 = new Test();

Test object2 = new Test();

//passing object instances to the runnable to make calls later

TestRunner runner = new TestRunner(object1,object2);

// you need to start atleast two threads to properly see the behaviour

Thread thread1 = new Thread(runner);

thread1.start();

Thread thread2 = new Thread(runner);

thread2.start();

}

}

class TestRunner implements Runnable {

Test object1;

Test object2;

public TestRunner(Test h1,Test h2) {

this.object1 = h1;

this.object2 = h2;

}

@Override

public void run() {

synchronizedEffectiveAsMethodsCalledOnSameObject(object1);

//noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(object1,object2);

}

// this method calls the method A and B with same object instance object1 hence simultaneous NOT possible

private void synchronizedEffectiveAsMethodsCalledOnSameObject(Test object1) {

try {

object1.methodA("object1");

object1.methodB("object1");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

// this method calls the method A and B with different object instances object1 and object2 hence simultaneous IS possible

private void noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects(Test object1,Test object2) {

try {

object1.methodA("object1");

object2.methodB("object2");

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

请注意,如果在不同的对象实例上调用方法,则可以按预期允许同时访问的输出差异。

带有noEffectOfSynchronizedAsMethodsCalledOnDifferentObjects()的输出注释 - 输出按顺序中的methodA in> 方法A Out ..方法B in> methodB Out

2FOTF.png

和同步有效的输出sMethodsCalledOnSameObject()评论 - 输出显示在突出显示的部分中Thread1和Thread0同时访问methodA -

pCcUJ.png

增加线程数将使其更加引人注目。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值