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

发布于 2025-01-20 23:46:23 字数 555 浏览 1 评论 0原文

基于提供的参数,在多个方法中使用了相同的实例。我们可以在这里考虑线程安全吗? 假设我们有2堂课, class main& 类演示

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

它将共享相同的 demo 实例。两种方法的效果都不同步。 还请描述春季注射案件,以@Autowired的注释

道歉,对错别字或其他错误表示歉意。

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
.

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

Apologies for typos or other mistakes.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

微凉徒眸意 2025-01-27 23:46:23

是的,它将共享相同的演示实例。但是计算是根据方法methodexample()进行的,是基于您对参数传递的值。
首先使用@Autowire,您必须在演示类上使用@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);
   }
}

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.
for using @autowire first you have to use @component annotation on Demo Class.

@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);
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文