Wait(); (threads)

3 respostas
lucasn

galera, estou tentando fazer um programa que possui 2 threads que atualizam um jlabel.
Então, ao apertar em um botão, é chamado o método wait() para bloquear uma das threads.
Teoricamente, era pra uma thread "dormir" e a outra thread continuar atualizando o jlabel. Contudo, ao chamar o wait(), toda a
app trava.

Alguém poderia me ajudar ?
obrigado!

class Update extends Thread
{
    private javax.swing.JLabel label;
    private int times;
    private int sleeptime;
    public Update( javax.swing.JLabel l, int st)
    {
        times = 0;
        label = l;
        sleeptime = st;
    }

    public synchronized void dormir() throws InterruptedException
    {
        this.wait();
    }

    @Override
    public void run()
    {
        while(times < 100)
        {
            try {
                label.setText((times++) + "");
                Thread.sleep(sleeptime);
            } catch (InterruptedException ex) {}
        }
        
    }
}



public class Main extends javax.swing.JFrame {

    Update u,v;

    public Main() {
        initComponents();

        u = new Update(texto,1000);
        v = new Update(texto2,500);

        u.start();
        v.start();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        texto = new javax.swing.JLabel();
        botao = new javax.swing.JButton();
        texto2 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        texto.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        texto.setText("0");

        botao.setText("wait();");
        botao.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoActionPerformed(evt);
            }
        });

        texto2.setFont(new java.awt.Font("DejaVu Sans", 0, 24)); // NOI18N
        texto2.setText("0");

        jLabel2.setText("Simple Threads");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(33, 33, 33)
                        .addComponent(texto)
                        .addGap(131, 131, 131)
                        .addComponent(texto2))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(78, 78, 78)
                        .addComponent(botao))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(56, 56, 56)
                        .addComponent(jLabel2)))
                .addContainerGap(37, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(texto2)
                    .addComponent(texto))
                .addGap(18, 18, 18)
                .addComponent(botao)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void botaoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_botaoActionPerformed
        try {
            // TODO add your handling code here:
            u.dormir();
        } catch (InterruptedException ex) { }
    }//GEN-LAST:event_botaoActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton botao;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel texto;
    private javax.swing.JLabel texto2;
    // End of variables declaration//GEN-END:variables

}

3 Respostas

fabiofalci

Dica: concorrência em swing use SwingWorker e entenda EDT.
http://java.sun.com/docs/books/tutorial/uiswing/concurrency/index.html

A

Não entendi. Por que você colocou no loop finito de execução da thread Update? Ao executar Thread.sleep(), ele já está parando a thread por um tempo, liberando a cpu para execução das outras threads. Se você quer testar a condição de ‘times < 100’, basta ter o ‘if’ dentro do while infinito. Se precisar, use synchronized para proteger as variáveis times, label e sleeptime.

lucasn

alexandrehdk:
Não entendi. Por que você colocou no loop finito de execução da thread Update? Ao executar Thread.sleep(), ele já está parando a thread por um tempo, liberando a cpu para execução das outras threads. Se você quer testar a condição de ‘times < 100’, basta ter o ‘if’ dentro do while infinito. Se precisar, use synchronized para proteger as variáveis times, label e sleeptime.

Na verdade, coloquei esse laço finito para fazer a thread incrementar até 100.

Quanto ao “freezing” do programa, achei a solução: http://www.guj.com.br/posts/list/85451.java

obrigado a todos!

Criado 24 de outubro de 2009
Ultima resposta 26 de out. de 2009
Respostas 3
Participantes 3