java线程间通信

线程间通信

线程间通信的模型有两种:共享内存和消息传递,以下方式都是基本这两种模型来实现的。
场景:两个线程,一个线程对当前数值加1,另一个线程对当前数值减1,要求用线程间通信,两个线程交替进行.

多线程编程步骤:

  • 第一步:创建资源类,在资源类中创建资源属性和操作方法
  • 第二步: 在资源类操作方法中分为以下三步:
    1. 判断
    2. 干活
    3. 通知
  • 第三步:创建多个线程,调用资源类的操作方法
  • 第四步:防止虚假唤醒问题

synchronized 方案

//第一步 创建资源类,定义属性和方法
class Share {
    //初始值
    private int number = 0;

    //+1的方法
    public synchronized void incr() throws InterruptedException {
        //第二步 判断 通知
        while (number != 0) {//while防止虚假唤醒
            //判断number值是否为0,如果不是0,等待
            this.wait();
        }
        //如果number值是0,就+1操作 干活
        number++;
        System.out.println(Thread.currentThread().getName() + "::" + number);

        //通知其他线程 通知
        this.notifyAll();

    }
    //-1方法
    public synchronized void decr() throws InterruptedException {
        //第二步 判断
        while(number != 1) {
            //判断number值是否为0,如果不是0,等待
            this.wait();
        }
        //如果number值是0,就-1操作 干活
        number--;
        System.out.println(Thread.currentThread().getName() + "::" + number);

        //通知其他线程 通知
        this.notifyAll();
    }
}
public class ThreadDemo1 {
    public static void main(String[] args) {
        //第三步 创建多个线程,调用资源类的操作方法
        Share share = new Share();
        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"AA").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"BB").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"CC").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"DD").start();


    }
}

结果:
在这里插入图片描述

Lock 方案

newCondition()方法:
关键字 synchronized 与 wait()/notify()这两个方法一起使用可以实现等待/通知模式, Lock 锁的 newContition()方法返回 Condition 对象,Condition 类也可以实现等待/通知模式。
用 notify()通知时,JVM 会随机唤醒某个等待的线程, 使用 Condition 类可以进行选择性通知, Condition 比较常用的两个方法:

  • await():会使当前线程等待,同时会释放锁,当其他线程调用 signal()时,线程会重新获得锁并继续执行。
  • signal():用于唤醒一个等待的线程。
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

//第一步 创建资源类,定义属性和操作方法
class Share {
    private int number = 0;

    //创建Lock
    private Lock lock =  new ReentrantLock();
    private Condition condition =  lock.newCondition();


    //+1
    public void incr() throws InterruptedException {
        //上锁
        lock.lock();
        try{
            //第二步:判断,防止虚假唤醒
            while(number != 0) {
                condition.await();
            }
            //干活
            number++;
            System.out.println(Thread.currentThread().getName() + "::" + number);
            //通知
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    //-1
    public void decr() throws InterruptedException {
        //上锁
        lock.lock();
        try{
            //判断,干活,通知
            while(number != 1) {
                condition.await();
            }
            number--;
            System.out.println(Thread.currentThread().getName() + "::" + number);

            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
public class ThreadDemo2 {
    public static void main(String[] args) {
        //第三步 创建多个线程,调用资源类的操作方法
        Share share = new Share();
        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"AA").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"BB").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.decr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"CC").start();

        new Thread(() -> {
            for(int i = 0; i< 10 ;i++) {
                try {
                    share.incr();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"DD").start();
    }
}

线程间定制化通信

需求: A 线程打印 5 次 A,B 线程打印 10 次 B,C 线程打印 15 次 C,按照此顺序循环 10 轮
在这里插入图片描述

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

//第一步 创建资源类
class ShareResource {
    //定义标志位
    private int flag = 1; // AA 1   BB 2    CC 3
    //创建Lock锁
    private Lock lock = new ReentrantLock();

    private Condition c1 = lock.newCondition();
    private Condition c2 = lock.newCondition();
    private Condition c3 = lock.newCondition();

    public void AA(int loop) throws InterruptedException {
        lock.lock();
        try{
            while(flag != 1) {
                c1.await();
            }
            System.out.println("第" + loop + "轮");
            for (int i = 0; i < 5; i++) {
                System.out.println("AA");
            }
            flag = 2;

            c2.signal();
        }finally {
            lock.unlock();
        }
    }

    public void BB(int loop) throws InterruptedException {
        lock.lock();
        try{
            while(flag != 2) {
                c2.await();
            }
            System.out.println("第" + loop + "轮");
            for (int i = 0; i < 10; i++) {
                System.out.println("BB");
            }
            flag = 3;
            c3.signal();
        }finally {
            lock.unlock();
        }
    }

    public void CC(int loop) throws InterruptedException {
        lock.lock();
        try{
            while(flag != 3) {
                c3.await();
            }
            System.out.println("第" + loop + "轮");
            for (int i = 0; i < 15; i++) {
                System.out.println("CC");
            }
            flag = 1;

            c1.signal();
        }finally {
            lock.unlock();
        }
    }

}
public class ThreadDemo3 {
    public static void main(String[] args) {
        ShareResource shareResource = new ShareResource();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.AA(i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.BB(i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    shareResource.CC(i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}

结果:
在这里插入图片描述

在这里插入图片描述

### 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、付费专栏及课程。

余额充值