成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

招行一面:Java 的線程如何通信?

開(kāi)發(fā) 后端
在 Java 中,線程是執(zhí)行的最小單元,那么線程之間是如何通信的呢?這篇文章我們一起來(lái)分析五種常用的方式。

在 Java中,線程是執(zhí)行的最小單元,那么線程之間是如何通信的呢?這篇文章我們一起來(lái)分析五種常用的方式。

  • 使用 wait()、notify() 和 notifyAll()
  • 使用 BlockingQueue
  • Exchanger
  • 使用 Locks 和 Condition
  • 使用 Semaphore

1. 使用 wait()、notify() 和 notifyAll()

Java的 Object 類提供了 wait()、notify() 和 notifyAll() 方法,這些方法可以用來(lái)實(shí)現(xiàn)線程之間的通信,這些方法必須在同步塊或同步方法中調(diào)用。

  • **wait()**:使當(dāng)前線程進(jìn)入等待狀態(tài),直到其他線程調(diào)用 notify() 或 notifyAll()。
  • **notify()**:?jiǎn)拘言谠搶?duì)象監(jiān)視器上等待的單個(gè)線程。
  • **notifyAll()**:?jiǎn)拘言谠搶?duì)象監(jiān)視器上等待的所有線程。

示例代碼:

class SharedResource {
    private int data;
    private boolean hasData = false;

    public synchronized void produce(int value) throws InterruptedException {
        while (hasData) {
            wait();
        }
        this.data = value;
        hasData = true;
        notify();
    }

    public synchronized int consume() throws InterruptedException {
        while (!hasData) {
            wait();
        }
        hasData = false;
        notify();
        return data;
    }
}

public class ProducerConsumerExample {
    public static void main(String[] args) {
        SharedResource resource = new SharedResource();

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = resource.consume();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

2. 使用 BlockingQueue

BlockingQueue 是Java中一個(gè)強(qiáng)大的接口,提供了線程安全的隊(duì)列操作,并且可以在生產(chǎn)者-消費(fèi)者模式中使用。BlockingQueue 不需要顯式地使用同步機(jī)制,它內(nèi)部已經(jīng)處理好了線程同步問(wèn)題。

示例代碼:

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class BlockingQueueExample {
    public static void main(String[] args) {
        BlockingQueue<Integer> queue = new ArrayBlockingQueue<>(10);

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    queue.put(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = queue.take();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

3. 使用 Locks 和 Condition

Java提供了 java.util.concurrent.locks 包,其中包含了 Lock 接口和 Condition 接口。Condition 提供了類似于 wait()、notify() 和 notifyAll() 的方法,但它們與 Lock 對(duì)象一起使用,提供了更靈活的線程通信機(jī)制。

示例代碼:

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResourceWithLock {
    private int data;
    private boolean hasData = false;
    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    public void produce(int value) throws InterruptedException {
        lock.lock();
        try {
            while (hasData) {
                condition.await();
            }
            this.data = value;
            hasData = true;
            condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public int consume() throws InterruptedException {
        lock.lock();
        try {
            while (!hasData) {
                condition.await();
            }
            hasData = false;
            condition.signal();
            return data;
        } finally {
            lock.unlock();
        }
    }
}

public class LockConditionExample {
    public static void main(String[] args) {
        SharedResourceWithLock resource = new SharedResourceWithLock();

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                    System.out.println("Produced: " + i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = resource.consume();
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

4. 使用 Exchanger

Exchanger 是一個(gè)用于線程間交換數(shù)據(jù)的同步點(diǎn)。兩個(gè)線程可以在此同步點(diǎn)交換數(shù)據(jù),Exchanger 的 exchange() 方法用于在兩個(gè)線程之間交換數(shù)據(jù)。

示例代碼:

import java.util.concurrent.Exchanger;

public class ExchangerExample {
    public static void main(String[] args) {
        Exchanger<Integer> exchanger = new Exchanger<>();

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    System.out.println("Produced: " + i);
                    exchanger.exchange(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    int data = exchanger.exchange(null);
                    System.out.println("Consumed: " + data);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

5. 使用 Semaphore

Semaphore 是一個(gè)計(jì)數(shù)信號(hào)量,通常用于限制對(duì)某些資源的訪問(wèn)。它可以用于控制線程訪問(wèn)共享資源的數(shù)量,這在某些情況下也可以用作線程間通信的機(jī)制。

示例代碼:

import java.util.concurrent.Semaphore;

class SemaphoreSharedResource {
    private int data;
    private Semaphore semaphore = new Semaphore(1);

    public void produce(int value) throws InterruptedException {
        semaphore.acquire();
        try {
            this.data = value;
            System.out.println("Produced: " + value);
        } finally {
            semaphore.release();
        }
    }

    public int consume() throws InterruptedException {
        semaphore.acquire();
        try {
            System.out.println("Consumed: " + data);
            return data;
        } finally {
            semaphore.release();
        }
    }
}

public class SemaphoreExample {
    public static void main(String[] args) {
        SemaphoreSharedResource resource = new SemaphoreSharedResource();

        Thread producer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.produce(i);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        Thread consumer = new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    resource.consume();
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        producer.start();
        consumer.start();
    }
}

結(jié)論

本文,我們分析了 Java線程通信的5種常見(jiàn)方式:

  • wait()/notify() 是一種低級(jí)別的同步機(jī)制,適合需要精細(xì)控制的場(chǎng)合;
  • BlockingQueue 和 Exchanger 提供了更高層次的抽象,簡(jiǎn)化了線程間的數(shù)據(jù)交換;
  • Locks 和 Condition 提供了更靈活的鎖機(jī)制,適合復(fù)雜的同步場(chǎng)景;
  • Semaphore 則用于控制資源訪問(wèn)。

在實(shí)際應(yīng)用中,需要選擇哪種方式取決于具體的應(yīng)用場(chǎng)景和需求。如何你有好的通信方式,歡迎評(píng)論區(qū)留言。

責(zé)任編輯:趙寧寧 來(lái)源: 猿java
相關(guān)推薦

2024-11-11 17:27:45

2024-09-27 16:33:44

2024-10-17 16:58:43

2022-05-11 22:15:51

云計(jì)算云平臺(tái)

2024-09-23 20:55:04

2009-07-30 14:38:36

云計(jì)算

2020-09-19 17:46:20

React Hooks開(kāi)發(fā)函數(shù)

2011-12-22 20:53:40

Android

2011-12-23 09:43:15

開(kāi)源開(kāi)放

2024-05-15 16:41:57

進(jìn)程IO文件

2023-12-01 09:11:33

大數(shù)據(jù)數(shù)據(jù)庫(kù)

2025-04-15 10:00:00

Feign負(fù)載均衡微服務(wù)

2024-10-22 15:25:20

2024-10-09 09:12:11

2025-03-20 09:59:55

Spring@ProfileJava

2022-05-10 22:00:41

UDPTCP協(xié)議

2024-07-22 19:31:34

2025-03-25 12:00:00

@Value?Spring開(kāi)發(fā)

2012-12-19 09:04:29

2025-04-01 08:40:00

HTTPRPC開(kāi)發(fā)
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)

主站蜘蛛池模板: 亚洲一区视频在线 | 一区中文字幕 | 欧美 日韩 亚洲91麻豆精品 | 欧美在线视频观看 | 亚洲视频免费播放 | 亚洲国产二区 | 一区二区三区欧美在线观看 | 亚洲九色 | 国产农村妇女精品一二区 | 久久国内 | 国产小视频在线观看 | 日韩欧美一区二区三区四区 | 日日噜噜噜夜夜爽爽狠狠视频, | a在线视频 | 色偷偷人人澡人人爽人人模 | 国产欧美精品在线 | 91国在线观看| 自拍偷拍精品 | a a毛片| 国产精品久久久久久久久免费软件 | 久久久国产精品 | 亚洲国产成人av好男人在线观看 | 国产精品1区 | 欧美在线视频二区 | 精品乱码一区二区三四区视频 | 在线亚洲免费视频 | 国产精品网址 | 精品视频一区二区三区在线观看 | 91网站在线看 | 天天天操操操 | 久久久免费 | 日韩一区二区三区四区五区 | 国产精品美女久久久久aⅴ国产馆 | 一区二区三区四区五区在线视频 | 亚洲欧美日韩国产综合 | 一区二区三区国产 | 久久午夜剧场 | 亚洲国产黄色av | 国产高清一区二区三区 | 久久精品视频91 | 国产日韩一区 |