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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay