首页 > Java > java教程 > 同步器的代码示例

同步器的代码示例

Barbara Streisand
发布: 2025-01-09 14:07:42
原创
860 人浏览过

Exemplos de código para os sincronizadores

以下是第 80 项中提到的同步器的代码示例,并附有使用说明以方便学习:

1。 CountDownLatch:用于线程协调的一次性屏障
CountDownLatch 允许一个或多个线程等待,直到其他线程执行的一组操作完成。

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
        }
    }
}

登录后复制

2。信号量:控制对共享资源的访问
信号量管理一组权限来控制对有限资源的访问。

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
            }
        }
    }
}

登录后复制

3。 CyclicBarrier:可重用屏障点上的同步
CyclicBarrier 在公共点(屏障)同步多个线程。当所有线程到达屏障点后可以重复使用。

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();
            }
        }
    }
}

登录后复制

4。 Phaser:高级动态线程同步
Phaser 与 CyclicBarrier 类似,但支持动态进入和离开线程。

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
        }
    }
}

登录后复制

这些示例可帮助您了解每个同步器的工作原理。您可以通过调整线程数量和计时来进行实验,观察对同步行为的影响。

以上是同步器的代码示例的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板