单例和线程 [英] singletons and threads

查看:92
本文介绍了单例和线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题是有关正在排队的线程.对于我的示例,我有一个Spring上下文.我在无状态类中有一个名为CalculateTax的方法.一个请求进入,创建了一个线程(tA),它最终进入CalculateTax方法.在同一时间范围"内,另一个请求进入,并创建另一个线程(tB).现在,这是我想了解的内容.在tA退出方法之前,AFAIK tB无法执行CalculateTax.这是真的吗?

My question is about threads being queued. For my example I have one Spring context. I have a method named CalculateTax in a stateless class. A request comes in, a thread is created (tA) and it eventually enters the CalculateTax method. Within the same "time frame" another request comes in and another thread is created (tB). Now, here is what I want to understand. AFAIK tB cannot execute CalculateTax until tA has exited the method. Is this true?

推荐答案

只要CalculateTax仅使用局部变量(即在方法中声明),就不会有任何线程同步问题,并且多个线程可以调用该方法而无需问题.

As long as CalculateTax only uses local variables (i.e. declared in the method), you will not have any thread sync issues and multiple threads can call the method without a problem.

但是,如果由于某种原因CalculateTax使用在类级别定义的变量,并且您使用的是Singleton模式(您用"singleton"标记了问题,所以我想是这样),则可能存在线程同步问题.

However if for some reason CalculateTax uses variables defined at the class level, and you are using the Singleton pattern (you tagged your question with "singleton", so I guess you are), you may have thread sync issues.

这篇关于单例和线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆