Home > Java > javaTutorial > Synchronization and Communication between Threads

Synchronization and Communication between Threads

Patricia Arquette
Release: 2024-11-27 07:37:09
Original
582 people have browsed it

Additional content:

Synchronization and Communication between Threads
Issue: Threads can interfere with each other when accessing shared data.

Solution:
Synchronized methods

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

Copy after login

Synchronized blocks:

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

Copy after login

Example of Communication:

Communication between threads using wait(), notify() and 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();
    }
}

Copy after login

Conclusion

  • Multi-threaded programming in Java allows you to create more efficient applications, especially on multicore systems.
  • It is important to correctly manage access to shared resources using synchronization.
  • The Thread class methods and the Runnable interface are powerful tools for working with multitasking.

Sincronização e Comunicação entre Threads

The above is the detailed content of Synchronization and Communication between Threads. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template