简体   繁体   English

如何等待线程完成以返回到先前的代码

[英]How to wait a thread to finish to back to the previous code

I have a question regarding threads. 我对线程有疑问。 I have a method that reads an Excel spreadsheet and saves the data in a database. 我有一个读取Excel电子表格并将数据保存在数据库中的方法。 However, this method also checks the contents of a cell is an expected value, and if not, a frame must be called for the user to choose the most appropriate option. 但是,此方法还检查单元格的内容是否为预期值,如果不是,则必须调用框架以供用户选择最合适的选项。 As it is written the code, it is not waiting for the frame open for the user to choose an option so he returns to the initial loop. 在编写代码时,它不会等待框架打开,以便用户选择一个选项,因此他返回到初始循环。 (For the post would not be too long, I have omitted parts of the code, leaving only what matters) The following parts of the code: (因为发布不会太长,所以我省略了代码的一部分,只保留了重要的内容)代码的以下部分:

public HashMap<String, Historico> importaDadosDoExcel(){
    HashMap<String, Historico> mapa = new HashMap<String, Historico>();
    HSSFCell cell= null;
    HSSFRow row = null;
    Historico update = new Historico();
    int rowsCount = 0;
    String[] statusStr = {"Aguardando Boleto", "Aguardando Lançamento", "Em Workflow","Liberado para Tesouraria", "Pago", "Outros"};
    String aux;
    for (int i = 1; i <= rowsCount; i++) {
        cell = row.getCell(ActvUtils.u.devolveNumColuna("D"));
        aux = ActvUtils.u.devolveCampoLido(cell);
        if (Arrays.asList(statusStr).contains(aux)) {
            update.setStatus(aux);
        }else{
            //Here, I would like the frame was called (passing as a parameter the value read in the cell) to which the user then chooses the best option, then, that choice was setted in the object.
            Runnable runnable = new EscolheStatus(aux); 
            Thread thread = new Thread(runnable);
            thread.start();
            //Here, I would like to read the option that the user chose on a string, some like:
            // String str = runnable.getStatus();
        }
    }
    return mapa;    
}

And now, my frame class: 现在,我的框架课:

public class EscolheStatus extends JFrame implements ActionListener,Runnable{


private String[] statusStr = {"Aguardando Boleto", "Aguardando Lançamento", "Em Workflow","Liberado para Tesouraria", "Pago", "Outros"};

private JRadioButton boleto;
private JRadioButton lancamento;
private JRadioButton workflow;
private JRadioButton tesouraria;
private JRadioButton pago;
private JRadioButton outros;

private String status;
private String statusEncontrado;

public EscolheStatus(String statusEncontrado){

    this.statusEncontrado = statusEncontrado;

    boleto = new JRadioButton(statusStr[0]);
    boleto.addActionListener(this);

    lancamento = new JRadioButton(statusStr[1]);
    lancamento.addActionListener(this);

    workflow = new JRadioButton(statusStr[2]);
    workflow.addActionListener(this);

    tesouraria = new JRadioButton(statusStr[3]);
    tesouraria.addActionListener(this);

    pago = new JRadioButton(statusStr[4]);
    pago.addActionListener(this);

    outros = new JRadioButton(statusStr[5]);
    outros.addActionListener(this);

    ButtonGroup group = new ButtonGroup();
    group.add(boleto);
    group.add(lancamento);
    group.add(workflow);
    group.add(tesouraria);
    group.add(pago);
    group.add(outros);

    JPanel radioPanel = new JPanel();
    radioPanel.setLayout(new GridLayout(6, 1));
    radioPanel.add(boleto);
    radioPanel.add(lancamento);
    radioPanel.add(workflow);
    radioPanel.add(tesouraria);
    radioPanel.add(pago);
    radioPanel.add(outros);

    radioPanel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Status '" + statusEncontrado + "' não reconhecido.  Escolha:"  ));
    setContentPane(radioPanel);  
    pack(); 
    this.setSize(350, 200);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);  
    this.setVisible(true);
    teste();

}

@Override
public void actionPerformed(ActionEvent ev) {
    Object opcao = ev.getSource();

    if(opcao.equals(boleto)){
        status = statusStr[0];
    }else if(opcao.equals(lancamento)){
        status = statusStr[1];
    }else if(opcao.equals(workflow)){
        status = statusStr[2];
    }else if(opcao.equals(tesouraria)){
        status = statusStr[3];
    }else if(opcao.equals(pago)){
        status = statusStr[4];
    }else if(opcao.equals(outros)){
        status = statusStr[5];
    }

    this.dispose();
}

public String getStatus() {
    return status;
}

public void setStatus(String status) {
    this.status = status;
}

@Override
public void run() {
    new EscolheStatus(statusEncontrado);

}

} }

Here's an example of what MasterBlaster suggested (if it's only to stop the thread to require user input): 这是MasterBlaster建议的示例(如果只是为了停止线程以要求用户输入):

Thread worker = new Thread(new Runnable() {      
  @Override
  public void run() {
    long start = System.currentTimeMillis();

    while( (System.currentTimeMillis() - start) < 10000) {          
      System.out.println( "opening dialog" );
      String result = JOptionPane.showInputDialog( "Tell me something!" );
      System.out.println("user entered: " + result);
    }        

    System.out.println("finished");
  }
});

worker.run();

This will open a dialog and wait for the input again and again until the thread ran for at least 10 seconds. 这将打开一个对话框,并一次又一次地等待输入,直到线程运行了至少10秒钟。

You should be able to adapt that to your needs. 您应该能够使其适应您的需求。

Of course, if multiple (worker) threads need to communicate you could use Thread.join() to wait for the other thread to finish or wait() and notify() if both threads need to run in parallel and one would just have to finish some task and then continue. 当然,如果需要通信多个(工作线程)线程,则可以使用Thread.join()等待另一个线程完成,或者使用wait()notify()如果两个线程都需要并行运行,而一个则只需要完成一些任务,然后继续。

Edit : // String str = runnable.getStatus(); 编辑// String str = runnable.getStatus(); implies you want to get some information about a still running thread. 表示您想获取有关仍在运行的线程的一些信息。 In that case you could use a shared object to write to and read from (you might need some synchronization). 在这种情况下,您可以使用共享对象进行写入和读取(可能需要进行一些同步)。

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

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