简体   繁体   English

同一个实例如何在 java 中的另一个 class 上以不同的方法工作

[英]how the same Instance work on different method on another class in java

Same instance is used in multiple method based on the argument providing.根据提供的参数,在多个方法中使用相同的实例。 can we consider thread safety here.我们可以在这里考虑线程安全吗? Let's assume that we've 2 class, Class Main & Class demo .假设我们有 2 class, Class Main & Class demo

Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
      return something
   }
}

Class Main {
   Demo demo = new Demo();

   returnType method1() {
      value = demo.methodExample(args);
   }
   
   returnType method2() {
      value = demo.methodExample(args);
   }
}

will it share same Demo Instance.它会共享相同的演示实例吗? And what of both method works asynchronously.这两种方法都是异步工作的。 please also describe the case in Spring Injecting by @AutoWired annotation还请在 Spring Injecting by @AutoWired annotation 中描述案例

Apologies for typos or other mistakes.对打字错误或其他错误表示歉意。

yes it will share same Demo instance.是的,它将共享相同的演示实例。 but the calculations are performed under method methodExample() is based on what value you are passed on parameters.但是计算是在方法 methodExample() 下执行的,它基于您在参数上传递的值。 for using @autowire first you have to use @component annotation on Demo Class.要首先使用@autowire,您必须在演示 Class 上使用@component 注释。

@Component
Class Demo {
   returnType methodExample(args...) {
      //based on the argument provide it returns
        return something
   }
}
Class Main {
   @Autowired
   Demo demo;

   returnType method1() {
      value = demo.methodExample(args);
   }

   returnType method2() {
      value = demo.methodExample(args);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM