国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) Java java教程 同步器的程式碼範(fàn)例

同步器的程式碼範(fàn)例

Jan 09, 2025 pm 02:07 PM

Exemplos de código para os sincronizadores

以下是第 80 項(xiàng)中提到的同步器的程式碼範(fàn)例,並附有使用說(shuō)明以方便學(xué)習(xí):

1。 CountDownLatch:用於執(zhí)行緒協(xié)調(diào)的一次性屏障
CountDownLatch 允許一個(gè)或多個(gè)執(zhí)行緒等待,直到其他執(zhí)行緒執(zhí)行的一組操作完成。

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。信號(hào)量:控制共享資源的存取
信號(hào)量管理一組權(quán)限來(lái)控制對(duì)有限資源的存取。

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:可重複使用屏障點(diǎn)上的同步
CyclicBarrier 在公共點(diǎn)(屏障)同步多個(gè)執(zhí)行緒。當(dāng)所有執(zhí)行緒到達(dá)屏障點(diǎn)後可以重複使用。

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:進(jìn)階動(dòng)態(tài)執(zhí)行緒同步
Phaser 與 CyclicBarrier 類(lèi)似,但支援動(dòng)態(tài)進(jìn)入和離開(kāi)執(zhí)行緒。

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

這些範(fàn)例可協(xié)助您了解每個(gè)同步器的工作原理。您可以透過(guò)調(diào)整線(xiàn)程數(shù)量和計(jì)時(shí)來(lái)進(jìn)行實(shí)驗(yàn),觀察對(duì)同步行為的影響。

以上是同步器的程式碼範(fàn)例的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線(xiàn)上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話(huà)題

hashmap和hashtable之間的區(qū)別? hashmap和hashtable之間的區(qū)別? Jun 24, 2025 pm 09:41 PM

HashMap與Hashtable的區(qū)別主要體現(xiàn)在線(xiàn)程安全、null值支持及性能方面。 1.線(xiàn)程安全方面,Hashtable是線(xiàn)程安全的,其方法大多為同步方法,而HashMap不做同步處理,非線(xiàn)程安全;2.null值支持上,HashMap允許一個(gè)null鍵和多個(gè)null值,Hashtable則不允許null鍵或值,否則拋出NullPointerException;3.性能方面,HashMap因無(wú)同步機(jī)制效率更高,Hashtable因每次操作加鎖性能較低,推薦使用ConcurrentHashMap替

為什麼我們需要包裝紙課? 為什麼我們需要包裝紙課? Jun 28, 2025 am 01:01 AM

Java使用包裝類(lèi)是因?yàn)榛緮?shù)據(jù)類(lèi)型無(wú)法直接參與面向?qū)ο癫僮?,而?shí)際需求中常需對(duì)象形式;1.集合類(lèi)只能存儲(chǔ)對(duì)象,如List利用自動(dòng)裝箱存儲(chǔ)數(shù)值;2.泛型不支持基本類(lèi)型,必須使用包裝類(lèi)作為類(lèi)型參數(shù);3.包裝類(lèi)可表示null值,用於區(qū)分未設(shè)置或缺失的數(shù)據(jù);4.包裝類(lèi)提供字符串轉(zhuǎn)換等實(shí)用方法,便於數(shù)據(jù)解析與處理,因此在需要這些特性的場(chǎng)景下,包裝類(lèi)不可或缺。

什麼是接口中的靜態(tài)方法? 什麼是接口中的靜態(tài)方法? Jun 24, 2025 pm 10:57 PM

StaticmethodsininterfaceswereintroducedinJava8toallowutilityfunctionswithintheinterfaceitself.BeforeJava8,suchfunctionsrequiredseparatehelperclasses,leadingtodisorganizedcode.Now,staticmethodsprovidethreekeybenefits:1)theyenableutilitymethodsdirectly

JIT編譯器如何優(yōu)化代碼? JIT編譯器如何優(yōu)化代碼? Jun 24, 2025 pm 10:45 PM

JIT編譯器通過(guò)方法內(nèi)聯(lián)、熱點(diǎn)檢測(cè)與編譯、類(lèi)型推測(cè)與去虛擬化、冗餘操作消除四種方式優(yōu)化代碼。 1.方法內(nèi)聯(lián)減少調(diào)用開(kāi)銷(xiāo),將頻繁調(diào)用的小方法直接插入調(diào)用處;2.熱點(diǎn)檢測(cè)識(shí)別高頻執(zhí)行代碼並集中優(yōu)化,節(jié)省資源;3.類(lèi)型推測(cè)收集運(yùn)行時(shí)類(lèi)型信息實(shí)現(xiàn)去虛擬化調(diào)用,提升效率;4.冗餘操作消除根據(jù)運(yùn)行數(shù)據(jù)刪除無(wú)用計(jì)算和檢查,增強(qiáng)性能。

什麼是實(shí)例初始器塊? 什麼是實(shí)例初始器塊? Jun 25, 2025 pm 12:21 PM

實(shí)例初始化塊在Java中用於在創(chuàng)建對(duì)象時(shí)運(yùn)行初始化邏輯,其執(zhí)行先於構(gòu)造函數(shù)。它適用於多個(gè)構(gòu)造函數(shù)共享初始化代碼、複雜字段初始化或匿名類(lèi)初始化場(chǎng)景,與靜態(tài)初始化塊不同的是它每次實(shí)例化時(shí)都會(huì)執(zhí)行,而靜態(tài)初始化塊僅在類(lèi)加載時(shí)運(yùn)行一次。

變量的最終關(guān)鍵字是什麼? 變量的最終關(guān)鍵字是什麼? Jun 24, 2025 pm 07:29 PM

InJava,thefinalkeywordpreventsavariable’svaluefrombeingchangedafterassignment,butitsbehaviordiffersforprimitivesandobjectreferences.Forprimitivevariables,finalmakesthevalueconstant,asinfinalintMAX_SPEED=100;wherereassignmentcausesanerror.Forobjectref

什麼是類(lèi)型鑄造? 什麼是類(lèi)型鑄造? Jun 24, 2025 pm 11:09 PM

類(lèi)型轉(zhuǎn)換有兩種:隱式和顯式。 1.隱式轉(zhuǎn)換自動(dòng)發(fā)生,如將int轉(zhuǎn)為double;2.顯式轉(zhuǎn)換需手動(dòng)操作,如使用(int)myDouble。需要類(lèi)型轉(zhuǎn)換的情況包括處理用戶(hù)輸入、數(shù)學(xué)運(yùn)算或函數(shù)間傳遞不同類(lèi)型的值時(shí)。需要注意的問(wèn)題有:浮點(diǎn)數(shù)轉(zhuǎn)整數(shù)會(huì)截?cái)嘈?shù)部分、大類(lèi)型轉(zhuǎn)小類(lèi)型可能導(dǎo)致數(shù)據(jù)丟失、某些語(yǔ)言不允許直接轉(zhuǎn)換特定類(lèi)型。正確理解語(yǔ)言的轉(zhuǎn)換規(guī)則有助於避免錯(cuò)誤。

什麼是工廠模式? 什麼是工廠模式? Jun 24, 2025 pm 11:29 PM

工廠模式用於封裝對(duì)象創(chuàng)建邏輯,使代碼更靈活、易維護(hù)、松耦合。其核心答案是:通過(guò)集中管理對(duì)象創(chuàng)建邏輯,隱藏實(shí)現(xiàn)細(xì)節(jié),支持多種相關(guān)對(duì)象的創(chuàng)建。具體描述如下:工廠模式將對(duì)象創(chuàng)建交給專(zhuān)門(mén)的工廠類(lèi)或方法處理,避免直接使用newClass();適用於多類(lèi)型相關(guān)對(duì)象創(chuàng)建、創(chuàng)建邏輯可能變化、需隱藏實(shí)現(xiàn)細(xì)節(jié)的場(chǎng)景;例如支付處理器中通過(guò)工廠統(tǒng)一創(chuàng)建Stripe、PayPal等實(shí)例;其實(shí)現(xiàn)包括工廠類(lèi)根據(jù)輸入?yún)?shù)決定返回的對(duì)象,所有對(duì)象實(shí)現(xiàn)共同接口;常見(jiàn)變體有簡(jiǎn)單工廠、工廠方法和抽象工廠,分別適用於不同複雜度的需求。

See all articles