简体   繁体   English

Java,多个线程,一次仅执行一个

[英]Java, multiple threads with only one executing at a time

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 我的主要问题是他们想要的类设计,我必须开始person类中的线程,但是bridge类需要能够等待并通知他们启动/停止

Any ideas how I can do this? 有什么想法可以做到吗?

You probably want to read up on wait and notify . 您可能想在wait阅读并notify There are tutorials with a google search. 有带有谷歌搜索的教程。

But after you understand them a bit, you want to have the person objects call wait . 但是,在对它们有所了解之后,您想要让person对象调用wait Then you want the bridge object to call notify . 然后,您希望桥对象调用notify When a person object returns from wait , it is their turn to cross (as I understand your problem.) When the person crosses, the bridge object would call notify again. 当人员对象从wait返回时,轮到他们交叉(据我所知,您的问题。)当人员交叉时,桥对象将再次调用notify

Make sure you synchronize correctly. 确保正确synchronize The tutorials should help. 这些教程应该会有所帮助。

Read this question as well: How to use wait and notify in Java? 还要阅读此问题: 如何在Java中使用等待和通知?

Lock an object like this: 锁定这样的对象:

// Bridge.java

public class Bridge {
private Object _mutex = new Object();

    public void cross(Person p)
        synchronized(_mutex) { 
             // code goes here
        }     
    }
}

That is one, probably the easiest, method.. 那是一种,可能是最简单的方法。

EDIT: 编辑:

even easier: 甚至更容易:

public class Bridge {
    public synchronized void cross(Person p)
    {
        // code goes here
    }
}

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 http://en.wikipedia.org/wiki/Mutex

Try java.util.concurrent: 试试java.util.concurrent:

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Executors.html#newSingleThreadExecutor%28%29 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". 此类将产生ExecutorService,您可以在其中提交“人员”。 And the Jobes are queued, one Person will cross at time. 乔布斯排队等候,一个人将同时穿越。

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

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