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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More