Java线程间通信与信号量

1. 信号量Semaphore

先说说Semaphore,Semaphore可以控制某个资源可被同时访问的个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。一般用于控制并发线程数,及线程间互斥。另外重入锁 ReentrantLock 也可以实现该功能,但实现上要复杂些。
功能就类似厕所有5个坑,假如有10个人要上厕所,那么同时只能有多少个人去上厕所呢?同时只能有5个人能够占用,当5个人中 的任何一个人让开后,其中等待的另外5个人中又有一个人可以占用了。另外等待的5个人中可以是随机获得优先机会,也可以是按照先来后到的顺序获得机会。
单个信号量的Semaphore对象可以实现互斥锁的功能,并且可以是由一个线程获得了“锁”,再由另一个线程释放“锁”,这可应用于死锁恢复的一些场合。

例子:

/**
 * @Description:
 * @param @param args
 * @return void 返回类型
 */
public static void main(String[] args) {
    // 线程池
    ExecutorService exec = Executors.newCachedThreadPool();
    // 只能5个线程同时访问
    final Semaphore semp = new Semaphore(5);
    // 模拟20个客户端访问
    for (int index = 0; index < 20; index++) {
        final int NO = index;
        Runnable run = new Runnable() {
            public void run() {
                try {
                    // 获取许可
                    semp.acquire();
                    System.out.println("获得Accessing: " + NO);
                    Thread.sleep((long) (Math.random() * 10000));
                    // 访问完后,释放
                    semp.release();
                    System.out.println("剩余可用信号-----------------"
                            + semp.availablePermits());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
        exec.execute(run);
    }
    // 退出线程池
    exec.shutdown();
}

输出结果(可以想想为什么会这样输出):
获得Accessing: 1
获得Accessing: 5
获得Accessing: 2
获得Accessing: 3
获得Accessing: 0
剩余可用信号-----------------1
获得Accessing: 4
剩余可用信号-----------------1
获得Accessing: 9
剩余可用信号-----------------1
获得Accessing: 8
剩余可用信号-----------------1
获得Accessing: 6
剩余可用信号-----------------1
获得Accessing: 10
剩余可用信号-----------------1
获得Accessing: 11
剩余可用信号-----------------1
获得Accessing: 12
剩余可用信号-----------------1
获得Accessing: 13
剩余可用信号-----------------1
获得Accessing: 7
剩余可用信号-----------------1
获得Accessing: 15
剩余可用信号-----------------1
获得Accessing: 16
剩余可用信号-----------------1
获得Accessing: 17
剩余可用信号-----------------1
获得Accessing: 14
剩余可用信号-----------------1
获得Accessing: 18
剩余可用信号-----------------1
获得Accessing: 19
剩余可用信号-----------------1
剩余可用信号-----------------2
剩余可用信号-----------------3
剩余可用信号-----------------4
剩余可用信号-----------------5

2. 使用PIPE作为线程间通信桥梁

Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。一进一出。先作为初步了解怎么使用。
值得注意的是该类在java.nio.channels下,说明该类属于nio方式的数据通信方式,那就使用Buffer来缓冲数据。

Pipe原理的图示:
Pipe原理图

  • Pipe就是个空管子,这个空管子一头可以从管子里往外读,一头可以往管子里写
  • 操作流程:

    • 1.首先要有一个对象往这个空管子里面写。写到哪里呢?这个空管子是有一点空间的,就在这个管子里。

写的时候就是写到管子本身包含的这段空间里的。这段空间大小是1024个字节。

  • 2.然后另一个对象才能将这个装满了的管子里的内容读出来。
上代码

package com.jx.test;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class testPipe {

    /**
     * @Description:
     * @param @param args
     * @return void 返回类型
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        // 创建一个管道
        Pipe pipe = Pipe.open();
        final Pipe.SinkChannel psic = pipe.sink();// 要向管道写数据,需要访问sink通道
        final Pipe.SourceChannel psoc = pipe.source();// 从读取管道的数据,需要访问source通道

        Thread tPwriter = new Thread() {

            public void run() {
                try {
                    System.out.println("send.....");
                    // 创建一个线程,利用管道的写入口Pipe.SinkChannel类型的psic往管道里写入指定ByteBuffer的内容
                    int res = psic.write(ByteBuffer
                            .wrap("Hello,Pipe!测试通讯.....".getBytes("utf-16BE")));
                    System.out.println("send size:" + res);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        Thread tPreader = new Thread() {
            public void run() {
                int bbufferSize = 1024 * 2;
                ByteBuffer bbuffer = ByteBuffer.allocate(bbufferSize);
                try {
                    System.out.println("recive.....");
                    // 创建一个线程,利用管道的读入口Pipe.SourceChannel类型的psoc将管道里内容读到指定的ByteBuffer中                    
                    int res = psoc.read(bbuffer);//数据未
                     System.out.println("recive size:"+res+" Content:" + ByteBufferToString(bbuffer));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };

        tPwriter.start();
        tPreader.start();
    }

    /**
     *ByteBuffer--> String的转换函数
     */
    public static String ByteBufferToString(ByteBuffer content) {
        if (content == null || content.limit() <= 0
                || (content.limit() == content.remaining())) {
            System.out.println("不存在或内容为空!");
            return null;
        }
        int contentSize = content.limit() - content.remaining();
        StringBuffer resultStr = new StringBuffer();
        for (int i = 0; i < contentSize; i += 2) {
            resultStr.append(content.getChar(i));
        }
        return resultStr.toString();
    }

}
### Java 线程间通信的方法和机制 Java 中的线程间通信是指多个线程通过某种方式共享数据或控制流,从而实现协同工作的过程。以下是几种常见的线程间通信方法及其工作机制。 #### 1. 使用 `wait()` 和 `notify()/notifyAll()` `Object` 类提供了三个用于线程间通信的核心方法:`wait()`、`notify()` 和 `notifyAll()`。这些方法必须在同步上下文中调用(即在 synchronized 块或方法中)。 - **`wait()`**: 当前线程进入等待状态,直到其他线程调用了同一对象上的 `notify()` 或 `notifyAll()` 方法。 - **`notify()`**: 随机唤醒一个正在此对象上等待的单个线程。 - **`notifyAll()`**: 唤醒在此对象上等待的所有线程。 这种方法适用于生产者消费者模式等场景[^1]。 ```java class SharedResource { private int data; private boolean available = false; public synchronized void produce(int value) throws InterruptedException { while (available) { wait(); // 如果资源不可用,则当前线程等待 } data = value; available = true; notifyAll(); // 通知消费线程可以继续运行 } public synchronized int consume() throws InterruptedException { while (!available) { wait(); // 如果资源不可用,则当前线程等待 } available = false; notifyAll(); // 通知生产线程可以继续运行 return data; } } ``` --- #### 2. 使用 `Lock` 和条件变量 除了传统的 `synchronized` 关键字外,还可以使用更高层次的锁机制——`ReentrantLock` 及其关联的条件队列 (`Condition`) 来实现线程间通信。这种方式更加灵活,允许指定不同的条件进行信号传递[^3]。 ```java import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; class SharedResourceWithLock { private final Lock lock = new ReentrantLock(); private final Condition condition = lock.newCondition(); private int data; private boolean available = false; public void produce(int value) throws InterruptedException { lock.lock(); try { while (available) { condition.await(); // 生产线程等待 } data = value; available = true; condition.signalAll(); // 唤醒消费线程 } finally { lock.unlock(); } } public int consume() throws InterruptedException { lock.lock(); try { while (!available) { condition.await(); // 消费线程等待 } available = false; condition.signalAll(); // 唤醒生产线程 return data; } finally { lock.unlock(); } } } ``` --- #### 3. 利用阻塞队列 Java 的 `java.util.concurrent` 包提供了一系列高效的线程安全集合类,其中最常用的便是阻塞队列(Blocking Queue),如 `LinkedBlockingQueue` 和 `ArrayBlockingQueue`。这类容器本身实现了生产和消费逻辑中的线程协调功能[^2]。 ```java import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; public class ProducerConsumerExample { static BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10); public static class Producer implements Runnable { @Override public void run() { try { for (int i = 0; i < 20; i++) { System.out.println("Producing " + i); queue.put(i); // 自动处理满队列的情况 Thread.sleep(100); } } catch (InterruptedException e) {} } } public static class Consumer implements Runnable { @Override public void run() { try { while (true) { Integer item = queue.take(); // 自动处理空队列的情况 System.out.println("Consumed " + item); if (item == 19) break; // 终止条件 } } catch (InterruptedException e) {} } } public static void main(String[] args) throws Exception { Thread producerThread = new Thread(new Producer()); Thread consumerThread = new Thread(new Consumer()); producerThread.start(); consumerThread.start(); producerThread.join(); consumerThread.join(); } } ``` --- #### 4. 使用原子变量 对于简单的计数器操作或其他轻量级需求,可以直接利用 `AtomicInteger`、`AtomicLong` 等原子类完成无锁化的线程间通信。 ```java import java.util.concurrent.atomic.AtomicInteger; public class AtomicCounter { private AtomicInteger counter = new AtomicInteger(0); public int incrementAndGet() { return counter.incrementAndGet(); // 完成自增并返回新值 } public int get() { return counter.get(); // 获取当前值 } } // 测试代码省略... ``` --- #### 5. 使用 `CountDownLatch`, `CyclicBarrier` 和 `Semaphore` 这些工具类分别适合不同类型的线程协作场景: - **`CountDownLatch`**: 让某个线程等待若干事件完成后才继续执行。 - **`CyclicBarrier`**: 多个线程到达屏障后再一起向前推进。 - **`Semaphore`**: 控制同时访问某资源的最大线程数量。 示例代码如下: ```java import java.util.concurrent.CountDownLatch; public class CountDownLatchExample { public static void main(String[] args) throws InterruptedException { CountDownLatch latch = new CountDownLatch(3); for (int i = 0; i < 3; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + " is done."); latch.countDown(); // 减少倒计数值 }).start(); } latch.await(); // 主线程会一直等到计数归零 System.out.println("All threads have finished their work."); } } ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值