简体   繁体   English

如何检查一个类的特定实例是否在java中运行?

[英]how to check if a specific instance of a class is running in java?

I have a class which will get data from socket. 我有一个类将从socket获取数据。 I should create 5 instance of this class according several condition. 我应该根据几个条件创建这个类的5个实例。 How can i check if a specific instant of this class is running, other ways creating that specific instance which is missing? 如何检查此类的特定瞬间是否正在运行,还有哪些方法可以创建缺少的特定实例? This is Some code snip: 这是一些代码片段:

public void checkReachabilityOfHosts(){

    String[] host = {"192.168.30.190", "", "", "", "" };

    for (String h : host) {
        if (h.length() > 0) {
            if (isHostReachable(h)) {
                DeviceByteReader deviceByteReader = new DeviceByteReader(h, 3001);
                deviceByteReader.setUpConnection();
                deviceByteReader.getSMessage();
                deviceByteReader.tearDownConnection();
            } else {
                return;
            }
        }else {
            return;
        }
    }
}

You can modify your class and add special id field to it. 您可以修改您的类并为其添加特殊的id字段。 This ID will be generated into the class constructor and you can always identify your instance. 此ID将生成到类构造函数中,您始终可以识别您的实例。 To generate ID use either time stamp in milliseconds or random number or static instance counter or, if you want to create really unique ID across the world use UUID.randomUUID() . 要生成ID,请使用以毫秒为单位的时间戳或随机数或静态实例计数器,或者,如果要在全球范围内创建真正唯一的ID,请使用UUID.randomUUID()

Other solution is just use System.identityHashCode(obj) . 其他解决方案只是使用System.identityHashCode(obj) This is unique across all objects within current instance of your JVM. 这在JVM的当前实例中的所有对象中都是唯一的。

Use the factory pattern : Give each instance a constant key (for example the IP address). 使用工厂模式 :为每个实例提供一个常量键(例如IP地址)。

The factory has a cache which uses the key to lookup existing instances. 工厂有一个缓存,它使用密钥来查找现有实例。 If there is no instance in the cache, create a new one. 如果缓存中没有实例,请创建一个新实例。

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

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