有关servlet多线程环境的问题 [英] Question regarding multi-threaded environment of servlet

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

问题描述

如果有servlet,则在servlet容器(例如Websphere)内.该servlet由某些线程执行.我想问一下,线程共享什么?它们之间如何共享变量?

If there is a servlet, inside a servlet container such as Websphere. The servlet are executed by some threads. I would like to ask, what does the threads share? How variables are shared between them?

它们是否具有以下变量的本地副本?

Do they have a local copy of the following variables?

1)私有/受保护/公共的最终信号灯许可=新的信号灯(50);

1) private/protected/public final Semaphore permits = new Semaphore(50);

2)私有/受保护/公共最终静态信号量许可=新的信号量(50);

2) private/protected/public final static Semaphore permits = new Semaphore(50);

3)私有/受保护/公共信号灯许可=新信号灯(50);

3) private/protected/public Semaphore permits = new Semaphore(50);

4)私有/受保护/公共静态信号量许可=新的信号量(50);

4) private/protected/public static Semaphore permits = new Semaphore(50);

我应该如何声明信号量,以便可以使用信号量来控制它们?我不希望他们给每个人一个信号量的副本.谢谢.

How should I declare the semaphore so that I can use semaphore to control them? I don't want them to have each of them a copy of the semaphore. Thanks.

推荐答案

每个线程都有自己的堆栈,但是所有线程共享相同的内存空间.考虑到这一点,一个实例可以在多个线程之间共享,因此可以共享其状态/属性.因此,我们需要使用同步或类似技术来照顾状态.

Each thread has its own stack, but all share the same memory space. With that in mind, a single instance can be shared, and so its state/properties, among multiple threads. Hence, we need to take care of state using synchronisation or similar techniques.

如果您定义一个静态变量,或者将使用servlet的一个实例-这很有可能,但不能保证,那么对于所有线程来说都是相同的.

If you define a static variable or a single instance of servlet will be used -- which is highly likely but no guarantee, then it would be the same for all threads.

尽管如此,您应该创建一个类,该类提供要在servlet中使用的单例信号量.这样,无论什么情况,servlet实例都将使用一个和相同的信号量对象.

Nonetheless, you should create a class which provide a singleton semaphore to be used in servlet. That way servlet instances will be using the one and the same semaphore object, no matter what.

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

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