1. java
  2. android
  3. c#
  4. .net
  5. javascript
  6. php
  7. jquery
  8. html
  9. sql

Synchronized / Wait / Notify

Pessoal eu estou tentando entender o metodo Sync mas até agora tudo que eu leio complica mais ainda a minha cabeça, eis aqui o meu código:

package gui;

import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class main extends javax.swing.JFrame {
    public main() {
        initComponents();
    }

    public synchronized void semaforo_01_start(){
        Thread worker;
        worker = new Thread(){
            public void run(){
                for(;;){
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_01_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/green_circle.png")));}
                    });
                    try {Thread.sleep(2000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_01_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/yellow_circle.png")));}
                    });
                    try {Thread.sleep(1000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_01_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/red_circle.png")));}
                    });
                }
            }
        };
        worker.start();
    }
    public synchronized void semaforo_02_start(){
        Thread worker;
        worker = new Thread(){
            public void run(){
                for(;;){
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_02_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/green_circle.png")));}
                    });
                    try {Thread.sleep(3000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_02_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/yellow_circle.png")));}
                    });
                    try {Thread.sleep(1000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_02_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/red_circle.png")));}
                    });
                }
            }
        };
        worker.start();
    }
    public synchronized void semaforo_03_start(){
        Thread worker;
        worker = new Thread(){
            public void run(){
                for(;;){
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_03_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/green_circle.png")));}
                    });
                    try {Thread.sleep(1000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_03_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/yellow_circle.png")));}
                    });
                    try {Thread.sleep(1000);} catch (InterruptedException ex){}
                    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                        public void run(){semaforo_03_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/red_circle.png")));}
                    });
                }
            }
        };
        worker.start();
    }
    public synchronized void botao_semaforo_4(){

    }

    public synchronized void semaforo_04_start(){

    }

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

        semaforo_01_txt = new javax.swing.JLabel();
        semaforo_02_txt = new javax.swing.JLabel();
        semaforo_03_txt = new javax.swing.JLabel();
        semaforo_04_txt = new javax.swing.JLabel();
        semaforo_01_img = new javax.swing.JLabel();
        semaforo_02_img = new javax.swing.JLabel();
        semaforo_03_img = new javax.swing.JLabel();
        semaforo_04_img = new javax.swing.JLabel();
        button_start = new javax.swing.JButton();
        button_semaforo_04 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        semaforo_01_txt.setText("Semaforo 1");

        semaforo_02_txt.setText("Semaforo 2");

        semaforo_03_txt.setText("Semaforo 3");

        semaforo_04_txt.setText("Semaforo 4");

        semaforo_01_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/white_circle.png"))); // NOI18N

        semaforo_02_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/white_circle.png"))); // NOI18N

        semaforo_03_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/white_circle.png"))); // NOI18N

        semaforo_04_img.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/white_circle.png"))); // NOI18N

        button_start.setText("Iniciar");
        button_start.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_startActionPerformed(evt);
            }
        });

        button_semaforo_04.setText("Ativar");
        button_semaforo_04.setEnabled(false);
        button_semaforo_04.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                button_semaforo_04ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(semaforo_01_txt)
                    .addComponent(semaforo_01_img)
                    .addComponent(button_start))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(semaforo_02_txt)
                    .addComponent(semaforo_02_img))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(semaforo_03_txt)
                    .addComponent(semaforo_03_img))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(semaforo_04_txt)
                    .addComponent(semaforo_04_img)
                    .addComponent(button_semaforo_04))
                .addContainerGap(52, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(35, 35, 35)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(semaforo_01_txt)
                    .addComponent(semaforo_02_txt)
                    .addComponent(semaforo_03_txt)
                    .addComponent(semaforo_04_txt))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(semaforo_04_img)
                    .addComponent(semaforo_01_img)
                    .addComponent(semaforo_02_img)
                    .addComponent(semaforo_03_img))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(button_semaforo_04)
                    .addComponent(button_start))
                .addContainerGap(46, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void button_startActionPerformed(java.awt.event.ActionEvent evt) {                                             
        // TODO add your handling code here:
        semaforo_01_start();
        semaforo_02_start();
        semaforo_03_start();
       // botao_semaforo_4();
        button_start.setEnabled(false);

    }                                            

    private void button_semaforo_04ActionPerformed(java.awt.event.ActionEvent evt) {                                                   
        // TODO add your handling code here:
       // semaforo_04_start();
    }                                                  

    public static void main(String args[]) throws UnsupportedLookAndFeelException {
        try{
             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }catch(ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex){  
            ex.printStackTrace(System.err);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new main().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton button_semaforo_04;
    private javax.swing.JButton button_start;
    static javax.swing.JLabel semaforo_01_img;
    private javax.swing.JLabel semaforo_01_txt;
    static javax.swing.JLabel semaforo_02_img;
    private javax.swing.JLabel semaforo_02_txt;
    static javax.swing.JLabel semaforo_03_img;
    private javax.swing.JLabel semaforo_03_txt;
    static javax.swing.JLabel semaforo_04_img;
    private javax.swing.JLabel semaforo_04_txt;
    // End of variables declaration                   
}

O que eu estou tentando fazer é, um método esperar o outro terminar para que o próximo continue.

Sema02 espera o Sema01 rodar, Sema03 espera o Sema02 rodar, o Sema01 espera o Sema03 rodar!

  1. Você vai ver essas setas em qualquer página de pergunta. Com elas, você pode dizer se uma pergunta ou uma resposta foram relevantes ou não.
  2. Edite sua pergunta ou resposta caso queira alterar ou adicionar detalhes.
  3. Caso haja alguma dúvida sobre a pergunta, adicione um comentário. O espaço de respostas deve ser utilizado apenas para responder a pergunta.
  4. Se o autor da pergunta marcar uma resposta como solucionada, esta marca aparecerá.
  5. Clique aqui para mais detalhes sobre o funcionamento do GUJ!

0 resposta

Não é a resposta que estava procurando? Procure outras perguntas com as tags threads java ou faça a sua própria pergunta.