DEV Community

FUNDAMENTOS JAVA
FUNDAMENTOS JAVA

Posted on

2

Sincronização e Comunicação entre Threads

Conteúdo adicional:

Sincronização e Comunicação entre Threads
Problema: Threads podem interferir umas nas outras ao acessar dados compartilhados.

Solução:
Métodos sincronizados

synchronized void synchronizedMethod() {
    // Código sincronizado
}

Enter fullscreen mode Exit fullscreen mode

Blocos sincronizados:

synchronized (this) {
    // Código sincronizado
}

Enter fullscreen mode Exit fullscreen mode

Exemplo de Comunicação:

Comunicação entre threads usando wait(), notify() e notifyAll():

class SharedResource {
    private boolean flag = false;

    synchronized void produce() {
        while (flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Producing...");
        flag = true;
        notify();
    }

    synchronized void consume() {
        while (!flag) {
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Consuming...");
        flag = false;
        notify();
    }
}

public class ThreadCommunication {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread producer = new Thread(resource::produce);
        Thread consumer = new Thread(resource::consume);

        producer.start();
        consumer.start();
    }
}

Enter fullscreen mode Exit fullscreen mode

Conclusão

  • A programação com várias threads em Java permite criar aplicativos mais eficientes, principalmente em sistemas multicore.
  • É importante gerenciar corretamente o acesso a recursos compartilhados usando sincronização.
  • Os métodos da classe Thread e a interface Runnable são ferramentas poderosas para trabalhar com multitarefa.

Image description

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more