从不同的类调用runnable方法

时间:2016-12-02 16:32:03

标签: java

在我的项目中,我有一个从本地磁盘加载大型模型的方法。加载模型大约需要15分钟,有时甚至更多。我想要做的是创建一个可运行的方法,它将模型加载一次,然后,从不同的类我调用此方法来执行一些代码。 事实上,我不知道如何实现这一目标,你能指导我吗? 这是简单的伪代码:

// class A has two method , load the model , and does some calculation 
Class A:  1.Runnable method: LoadModel();
          2.Mehtod2: distance();
// here i would like to run this programe anytime, pass some parameters and call the method "distance" in class A
Class B: 1.import Loadmodel() class and invoke distance ();
在我看来,我想创建类似于服务器而不是服务器的东西:)

更新:以下代码是我到目前为止所尝试的。

public class load implements Runnable {

    WordVectors wordVectors;

    public void run() {
        try {
            load();
        } catch (FileNotFoundException ex) {
            java.util.logging.Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            java.util.logging.Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void load() throws FileNotFoundException, UnsupportedEncodingException {
        //Your display method implementation.
          wordVectors = WordVectorSerializer.loadTxtVectors(new File("glove.twitter.27B.200d.txt"));
    }

    public double Simmiraty(String a, String b){
        return wordVectors.similarity(a,b);
    }

    public static void main(String[] args) {
        load  Obj= new load ();
        Obj.run();
    }
}

第二课:

public class B{

    public static  void main(String[] args) throws Exception {
        load ob =new load();
        System.out.println( ob.Simmiraty("iphone", "battery"));
    }
}

我必须使用上面的代码:  1.一旦加载模型,它就会停止运行。  我不能从第一课那里调用任何方法。

1 个答案:

答案 0 :(得分:0)

public class Load implements Runnable{

    private InputStream stream;
    private static final Load instance;
    private WordVectors wordVectors;

    static {
        instance = new Load();
        instance.run();
    }

    public static Load GetLoad(){
        return instance;
    }

    private Load(){
        if(instance != null)
            throw new UnsupportedOperationException();
    }

    public voir run() {
        if(wordVectors != null) 
            throw new UnsupportedOperationException();
        try {
            load();
        } catch (Exception ex) {
            Logger.getLogger(load.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void load() throws FileNotFoundException, UnsupportedEncodingException {
        stream = new InputStream(new File("glove.twitter.27B.200d.txt"));
        wordVectors = WordVectorSerializer.loadTxtVectors(stream,false);
    }

    public void interrupt(){
        if(stream != null)
            stream.close();
    }

    public double Simmiraty(String a, String b){
        return wordVectors.similarity(a,b);
    }

    public static void main(){
        Load load = GetLoad();
    }

}

public class B{

    public void function(){
        Load load = Load.GetLoad();
    }

}