Home Java javaTutorial Code examples for the synchronizers

Code examples for the synchronizers

Jan 09, 2025 pm 02:07 PM

Exemplos de código para os sincronizadores

Here are code examples for the synchronizers mentioned in item 80, with explanations of use to facilitate the study:

1. CountDownLatch: Single-use barrier for thread coordination
CountDownLatch allows one or more threads to wait until a set of operations performed by other threads is completed.

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int numberOfWorkers = 3;
        CountDownLatch latch = new CountDownLatch(numberOfWorkers);

        for (int i = 0; i < numberOfWorkers; i++) {
            new Thread(new Worker(latch, "Worker-" + i)).start();
        }

        System.out.println("Waiting for workers to finish...");
        latch.await(); // Aguarda todos os trabalhadores chamarem latch.countDown()
        System.out.println("All workers are done. Proceeding...");
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;
        private final String name;

        Worker(CountDownLatch latch, String name) {
            this.latch = latch;
            this.name = name;
        }

        @Override
        public void run() {
            System.out.println(name + " is working...");
            try {
                Thread.sleep((long) (Math.random() * 2000)); // Simula trabalho
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println(name + " finished.");
            latch.countDown(); // Decrementa o contador
        }
    }
}

Copy after login

2. Semaphore: Control access to shared resources
Semaphore manages a set of permissions to control access to limited resources.

import java.util.concurrent.Semaphore;

public class SemaphoreExample {
    public static void main(String[] args) {
        int permits = 2; // Número de permissões disponíveis
        Semaphore semaphore = new Semaphore(permits);

        for (int i = 1; i <= 5; i++) {
            new Thread(new Task(semaphore, "Task-" + i)).start();
        }
    }

    static class Task implements Runnable {
        private final Semaphore semaphore;
        private final String name;

        Task(Semaphore semaphore, String name) {
            this.semaphore = semaphore;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                System.out.println(name + " is waiting for a permit...");
                semaphore.acquire(); // Adquire uma permissão
                System.out.println(name + " got a permit and is working...");
                Thread.sleep((long) (Math.random() * 2000)); // Simula trabalho
                System.out.println(name + " is releasing a permit.");
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            } finally {
                semaphore.release(); // Libera a permissão
            }
        }
    }
}

Copy after login

3. CyclicBarrier: Synchronization on reusable barrier points
CyclicBarrier synchronizes multiple threads at a common point (barrier). It can be reused after all threads reach the barrier point.

import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierExample {
    public static void main(String[] args) {
        int numberOfThreads = 3;
        CyclicBarrier barrier = new CyclicBarrier(numberOfThreads, () -> {
            System.out.println("All threads have reached the barrier. Proceeding...");
        });

        for (int i = 0; i < numberOfThreads; i++) {
            new Thread(new Task(barrier, "Thread-" + i)).start();
        }
    }

    static class Task implements Runnable {
        private final CyclicBarrier barrier;
        private final String name;

        Task(CyclicBarrier barrier, String name) {
            this.barrier = barrier;
            this.name = name;
        }

        @Override
        public void run() {
            try {
                System.out.println(name + " is performing some work...");
                Thread.sleep((long) (Math.random() * 2000)); // Simula trabalho
                System.out.println(name + " reached the barrier.");
                barrier.await(); // Aguarda todas as threads chegarem à barreira
                System.out.println(name + " passed the barrier.");
            } catch (Exception e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}

Copy after login

4. Phaser: Advanced and dynamic thread synchronization
Phaser is similar to CyclicBarrier, but supports dynamically entering and leaving threads.

import java.util.concurrent.Phaser;

public class PhaserExample {
    public static void main(String[] args) {
        Phaser phaser = new Phaser(1); // Registra o "partida principal"

        for (int i = 0; i < 3; i++) {
            new Thread(new Task(phaser, "Task-" + i)).start();
        }

        // Avança para a próxima fase após garantir que todas as threads registradas concluíram
        System.out.println("Main thread waiting for phase 1 completion...");
        phaser.arriveAndAwaitAdvance();

        System.out.println("All tasks completed phase 1. Main thread moving to phase 2...");
        phaser.arriveAndDeregister(); // Desregistra a thread principal
    }

    static class Task implements Runnable {
        private final Phaser phaser;
        private final String name;

        Task(Phaser phaser, String name) {
            this.phaser = phaser;
            this.name = name;
            phaser.register(); // Registra a thread no Phaser
        }

        @Override
        public void run() {
            System.out.println(name + " is working on phase 1...");
            try {
                Thread.sleep((long) (Math.random() * 2000)); // Simula trabalho
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println(name + " completed phase 1.");
            phaser.arriveAndAwaitAdvance(); // Indica chegada na fase atual e aguarda

            System.out.println(name + " is working on phase 2...");
            try {
                Thread.sleep((long) (Math.random() * 2000)); // Simula trabalho
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            System.out.println(name + " completed phase 2.");
            phaser.arriveAndDeregister(); // Indica chegada e desregistra
        }
    }
}

Copy after login

These examples help you understand how each synchronizer works. You can experiment by adjusting the thread numbers and timings to observe the effects on the synchronization behavior.

The above is the detailed content of Code examples for the synchronizers. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles