Java,多个线程,一次只执行一个
我正在做一项作业,必须创建两个类,一个代表一个人,另一个代表一座桥梁。任何时候只有一个人可以“过”桥,但可能会有人等待过桥
我通过多线程轻松实现了这一点,允许多人同时过桥,但在更改它以允许多人过桥时遇到了问题只有一个线程要运行...
我的主要问题是他们想要的类设计,我必须在人员类中启动线程,但是桥类需要能够等待并通知他们启动/停止
任何想法我如何可以这样做吗?
I am working on an assignment and have to create two classes, one represents a person, and the other representing a bridge. Only one person can be "crossing" the bridge at any one time, but there could be people waiting to cross
I easily implemented this with multi-threading allowing for multiple people to cross at once, but I am having issues when changing it to allow only one thread to run...
My main problem is the class design they want, I have to begin the threads within the person class, but the bridge class needs to be able to wait and notify them to start/stop
Any ideas how I can do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能想阅读
wait
和notify
。 google一下就有教程了。但在您稍微了解它们之后,您希望让 person 对象调用
wait
。然后您希望桥对象调用notify
。当一个人对象从wait
返回时,轮到他们穿越(据我了解你的问题)。当人穿越时,桥对象会再次调用notify
。确保正确
同步
。教程应该有帮助。另请阅读这个问题:如何在 Java 中使用等待和通知?< /a>
You probably want to read up on
wait
andnotify
. There are tutorials with a google search.But after you understand them a bit, you want to have the person objects call
wait
. Then you want the bridge object to callnotify
. When a person object returns fromwait
, it is their turn to cross (as I understand your problem.) When the person crosses, the bridge object would callnotify
again.Make sure you
synchronize
correctly. The tutorials should help.Read this question as well: How to use wait and notify in Java?
像这样锁定一个对象:
这是一个,可能是最简单的方法。
编辑:
甚至更简单:
Lock an object like this:
That is one, probably the easiest, method..
EDIT:
even easier:
我相信作业要求您做的是使用(或实现)互斥体来访问共享资源,即桥。 http://en.wikipedia.org/wiki/Mutex
I believe what the assignment is asking you to do is to use (or implement) a mutex for access to the shared resource, aka the bridge. http://en.wikipedia.org/wiki/Mutex
尝试java.util.concurrent:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29
这个类将产生一个 ExecutorService,您可以在其中提交“人员”。乔布斯们都在排队,一次就会有一个人穿过。
Try java.util.concurrent:
http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29
This class wil produce an ExecutorService, where you can submit yout "Persons". And the Jobes are queued, one Person will cross at time.