Java:如何比较不同线程中的对象

发布于 2024-11-18 11:53:01 字数 2243 浏览 1 评论 0原文

我有一台服务器监听来自客户端的数据。一旦客户端发送数据,它将进入一个线程。这样,每个线程都有一个数据。 revFeaturePoints 是服务器从客户端接收的数据。

每个 revFeaturePoints 有一个浮点数组,我想计算不同线程中不同 revFeaturePoints 之间的欧几里德距离?

我不知道如何让一个线程访问其他线程中的另一个 revFeaturePoints ?

这是代码:

public class MyServer {

public static void main(String[] args) throws IOException{
    ServerSocket serverSocket = null;

    //bind a serverSocket to the port and listen
    try{
        serverSocket = new ServerSocket(8888);
        System.out.println("Listening: 8888");
    }catch(IOException e){
        e.printStackTrace();
    }

    while(true)
        new MyServerThread(serverSocket.accept()).start();
}   
}

public class MyServerThread  extends Thread{
//Create a socket for each client
private Socket socket = null;
private ObjectInputStream dataInputStream = null;
private ObjectOutputStream dataOutputStream = null;
private ArrayList<FeaturePointList> revFeaturePoints = null;

//constructor
public MyServerThread(Socket socket){
    super("MyServerThread");
    this.socket = socket;
}

@SuppressWarnings("unchecked")
public void run(){
    try{            
        dataOutputStream = new ObjectOutputStream(socket.getOutputStream());
        dataInputStream = new ObjectInputStream(socket.getInputStream());
        System.out.println("ip: "+ socket.getInetAddress());
        revFeaturePoints = (ArrayList<FeaturePointList>) dataInputStream.readObject();          

    }catch(IOException e){
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    finally{
        if(socket!=null){
            try{
                socket.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(dataInputStream!=null){
            try{
                dataInputStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }               
        }
        if(dataOutputStream!=null){
            try{
                dataOutputStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }               
        }

    }
}

}

I have a server listening data from clients. Once a client sends data, it will go into a thread. Thus, each thread has a data. revFeaturePoints is the data which the server receives from clients.

Each revFeaturePoints has a float array, I want to compute the Euclidean distance between different revFeaturePoints in different thread?

I do not know how can let one thread to access another revFeaturePoints in other threads?

Here is the code:

public class MyServer {

public static void main(String[] args) throws IOException{
    ServerSocket serverSocket = null;

    //bind a serverSocket to the port and listen
    try{
        serverSocket = new ServerSocket(8888);
        System.out.println("Listening: 8888");
    }catch(IOException e){
        e.printStackTrace();
    }

    while(true)
        new MyServerThread(serverSocket.accept()).start();
}   
}

public class MyServerThread  extends Thread{
//Create a socket for each client
private Socket socket = null;
private ObjectInputStream dataInputStream = null;
private ObjectOutputStream dataOutputStream = null;
private ArrayList<FeaturePointList> revFeaturePoints = null;

//constructor
public MyServerThread(Socket socket){
    super("MyServerThread");
    this.socket = socket;
}

@SuppressWarnings("unchecked")
public void run(){
    try{            
        dataOutputStream = new ObjectOutputStream(socket.getOutputStream());
        dataInputStream = new ObjectInputStream(socket.getInputStream());
        System.out.println("ip: "+ socket.getInetAddress());
        revFeaturePoints = (ArrayList<FeaturePointList>) dataInputStream.readObject();          

    }catch(IOException e){
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 
    finally{
        if(socket!=null){
            try{
                socket.close();
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        if(dataInputStream!=null){
            try{
                dataInputStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }               
        }
        if(dataOutputStream!=null){
            try{
                dataOutputStream.close();
            }catch(IOException e){
                e.printStackTrace();
            }               
        }

    }
}

}

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

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

发布评论

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

评论(5

凉栀 2024-11-25 11:53:01

一种简单的方法是将同步方法放入返回数据的 MyServerThread 中。

另一种方法是使用 BlockingQueue 并将数据结果放入队列中,并将结果作为生产者-消费者模式。请参阅此处了解一种方法做这个。

A simple way would be putting a synchronized method in MyServerThread that returns the data.

Another way of doing it would be to use a BlockingQueue and place the data result in a queue and taking the results from this as a producer-consumer pattern. See here for a way of doing this.

过度放纵 2024-11-25 11:53:01

如果您的 MyServerThread 类将数据存储到某个字段中,您可以从 MyServerThread 的多个实例访问该字段。

If your MyServerThread class stashes the data into a field, you can access that field from multiple instances of MyServerThread.

定格我的天空 2024-11-25 11:53:01

您可以通过使用共享结构和正确的同步在线程之间共享数据。例如,您可以在 MyServerThread 中有一个 ConcurrentHashMap<'threadname', data>,其中每个线程放置其数据并在其他线程中搜索数据。

也就是说,您应该评估您的架构。如果 N 个线程必须检查其他 N-1 个线程正在对数据执行什么操作,那么您正在为性能灾难做好准备。也许,您想要做的是在您的体系结构中创建一些分层,其中许多 ServerThread 收集请求并将它们放置在并发共享结构(例如队列)中。然后另一组工作人员正在比较和处理数据并在协作系统中产生结果。查看生产者-消费者模式

You can share the data among threads by using a shared structure and correct synchronization. For example, you could have a ConcurrentHashMap<'threadname', data> in MyServerThread where each thread puts its data and search for data in other threads.

That said, you should evaluate your architecture. If N threads have to check what the other N-1 threads are doing with data, you are preparing a recipe for performance disaster. Probably, what you would like to do is to create some layering in your architecture, where a number of ServerThreads are gathering the request and placing them in a concurrent shared structure (e.g queues). Then another set of workers are comparing and processing the data and producing results in a collaborative system. Have a look at the producer-consumer pattern.

忘年祭陌 2024-11-25 11:53:01

[确实是一条评论,但不适合;)]

maasg 的答案在一般意义上是相当正确的,但我相信您现在正在考虑设计困难,而不是 Java 线程实现本身。

您的服务器(按原样)在每个连接请求上触发一个一次性线程,该线程只是从客户端读取一个对象,然后关闭连接。传递的对象被放入(服务器线程)实例范围的对象中(退出 run() 后会被及时垃圾收集)。

完全不清楚——因此给人的印象是这是一个设计问题——如何确定要比较哪两个线程,或者就此而言,什么保证一开始就会有(总是)两个并发线程。

从逻辑上讲,您显然在服务器线程和域中的一些有意义的事物之间存在某种特定于域的关联。这种关系需要用代码来体现,但首先我们要明白这个区别和关系是什么。

[really a comment but won't fit ;)]

maasg's answer is quite correct in the general sense, but I believe you are right now looking at design difficulties and not Java threaded implementation per se.

You server (as is) fires off a disposable thread on each connect request, and this thread simply reads one object from the client and then closes the connection. The passed object is put in a (server thread) instance scoped object (which is duly garbage collected after you exit run()).

It is completely unclear -- and thus the impression that this is a design problem -- how you determine which 2 threads to compare, or for that matter, what guarantees you have that there will be (always) 2 concurrent threads to begin with.

Logically, you clearly have some domain specific association between a server thread and some meaningful matter in your domain. This relationship needs to be embodied in code, but first we need to understand what is this distinction and relationship.

Hello爱情风 2024-11-25 11:53:01

对象不是“在不同的线程中”。对象是其他不同对象的成员,通常通过“get”方法引用。完全忘记线程问题,它是无关紧要的。您只想将对象 A 的成员与对象 B 的成员进行比较。这一切如常。

Objects aren't 'in different threads'. Objects are members of other different objects, usually referenced via 'get' methods. Forget about the thread issue entirely, it is irrelevant. You just want to compare a member of object A with a member of object B. This is just business as usual.

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