【无标题】object,wait,notifyAll

在 Java 中,Object类提供了wait()方法,用于线程间的协作和同步。wait()方法使得当前线程暂停执行,并释放当前对象的锁,直到其他线程调用该对象的notify()或notifyAll()方法将其唤醒。这是实现线程间通信和同步的重要机制之一。

wait()方法的使用

wait()方法定义在Object类中,因此所有 Java 对象都继承了这个方法。它有三种重载形式:

• wait():使当前线程等待,直到其他线程调用该对象的notify()或notifyAll()方法。

• wait(long timeout):使当前线程等待,直到其他线程调用该对象的notify()或notifyAll()方法,或者指定的超时时间到期。

• wait(long timeout, int nanos):使当前线程等待,直到其他线程调用该对象的notify()或notifyAll()方法,或者指定的超时时间到期(精确到纳秒)。

使用wait()和notify()的注意事项

• 必须在同步块中调用:wait()和notify()方法必须在同步块(synchronized块)中调用,否则会抛出IllegalMonitorStateException异常。

• 释放锁:调用wait()方法时,当前线程会释放当前对象的锁。

• 线程中断:如果线程被中断,wait()方法会抛出InterruptedException异常。

• 超时机制:如果指定了超时时间,线程会在超时后自动唤醒。

示例代码

以下是一个简单的生产者-消费者示例,展示如何使用wait()和notify()方法来实现线程间的同步。

生产者-消费者示例

java 复制代码
import java.util.LinkedList;
import java.util.Queue;

public class ProducerConsumerExample {
    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        Thread producerThread = new Thread(new Producer(buffer));
        Thread consumerThread = new Thread(new Consumer(buffer));

        producerThread.start();
        consumerThread.start();
    }
}

class Buffer {
    private Queue<Integer> queue = new LinkedList<>();
    private int capacity;

    public Buffer(int capacity) {
        this.capacity = capacity;
    }

    public synchronized void put(int value) throws InterruptedException {
        while (queue.size() == capacity) {
            wait(); // 等待,直到有空间放置新元素
        }
        queue.add(value);
        notifyAll(); // 唤醒等待的消费者线程
    }

    public synchronized int get() throws InterruptedException {
        while (queue.isEmpty()) {
            wait(); // 等待,直到有元素可消费
        }
        int value = queue.poll();
        notifyAll(); // 唤醒等待的生产者线程
        return value;
    }
}

class Producer implements Runnable {
    private Buffer buffer;

    public Producer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                System.out.println("Produced: " + i);
                buffer.put(i);
                Thread.sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable {
    private Buffer buffer;

    public Consumer(Buffer buffer) {
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            try {
                int value = buffer.get();
                System.out.println("Consumed: " + value);
                Thread.sleep((int)(Math.random() * 1000));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

代码说明

• Buffer类:

• 使用synchronized方法确保线程安全。

• put方法在队列满时调用wait(),在添加元素后调用notifyAll()。

• get方法在队列空时调用wait(),在移除元素后调用notifyAll()。

• Producer类:

• 生产者线程调用Buffer的put方法生产数据。

• Consumer类:

• 消费者线程调用Buffer的get方法消费数据。

使用场景
wait()和notify()方法通常用于以下场景:

• 生产者-消费者模式:生产者线程生成数据,消费者线程消费数据。

• 线程间通信:多个线程需要基于某些条件进行协作。

• 资源管理:多个线程共享有限资源,需要同步访问。

总结
wait()方法是 Java 中实现线程间同步的重要工具之一。它使得线程可以暂停执行并释放锁,直到其他线程通过notify()或notifyAll()方法将其唤醒。通过合理使用wait()和notify(),可以实现高效的线程间协作和同步。

相关推荐
宸津-代码粉碎机3 小时前
OpenAI 连夜迎战 Grok Bot 和 Muse:AI 智能体从 “会聊天” 到 “能办事”,现在入场还来得及吗
java·大数据·人工智能·分布式·python
chenbingjie_c4 小时前
C++ 进阶核心知识点总结:模板、内存分区、new/delete、内存池
开发语言·c++
噢,我明白了4 小时前
java中唯一键和幂等键的应用
java·后端
程序猿乐锅4 小时前
【黑马点评 | 第八篇】Redisson分布式锁
java·数据库·spring boot·redis·分布式·spring·缓存
考虑考虑5 小时前
synchronized字符串常量
java·后端·java ee
长谷深风1115 小时前
Tool与Skill:AI能力设计的分水岭
java·人工智能·ai·大模型·aiagent
m0_587383005 小时前
广州24小时自助健身房解决方案实战指南与系统部署要点
java·spring·小程序·架构·需求分析
Escalating_xu5 小时前
【C 语言】深入理解指针(1·下):指针运算、野指针、assert 与传址实战
java·c语言·开发语言
实心儿儿5 小时前
Qt — Qt 事件
开发语言·qt
周杰偷奶茶5 小时前
【Java】数据类型与变量
java·开发语言