线程完成其工作后返回一个值

时间:2015-06-11 23:38:34

标签: java multithreading

我尝试用java实现带有线程的Observer模式。我想要做的是从新线程中返回一个值。

在这个question中,有人建议使用Observer模式,我想使用它。

我有以下代码:

/*Observable*/
public class QRExplorer extends Observable implements Runnable {
private String md5;

public String getMD5()
{
    return md5;
}
private void setMD5(String value)
{
    this.md5 = value;
    setChanged();
    notifyObservers();
}
@Override
public void run() {
 // do some stuff   
 // here I should obtain a string and I want return that
 setMD5("value");
}

}

/*Observer*/

public class Observador implements Observer {

private QRExplorer observado = null;

public Observador(QRExplorer observado)
{
    this.observado = observado;
}

@Override
public void update(Observable o, Object arg) {
    if(o == observado)
    {
        System.out.println("Something has changed ¬¬: "+observado.getMD5());
    }
}

}

/*Principal class*/
public class MainView extends javax.swing.JFrame implements ThreadFactory{

private RKeyListener listener;
private Webcam camara;
private Executor creador = Executors.newSingleThreadExecutor(this);
private Observador observador;
private QRExplorer explorer;

/*Nothing relevant*/

private void pCamaraMouseClicked(java.awt.event.MouseEvent evt)  {                                     
    creador.execute(explorer);
} 



@Override
public Thread newThread(Runnable r) {
    Thread t = new Thread(r);
    Observable obs = (Observable)t;// but Netbeans tells me: incompatible types: Thead cannot be converted to Observable
    obs.addObserver(observador);
    return t;
}

}

1 个答案:

答案 0 :(得分:0)

试试

class Object-A {
  var b: Object-B }