多案例理解Object的wait,notify,notifyAll与Thread的sleep,yield,join等方法

简介: 多案例理解Object的wait,notify,notifyAll与Thread的sleep,yield,join等方法


1. wait,notify,notifyAll方法详解

1.1 wait-notify用法

  • 我们创建两个线程类,用一个object对象加锁,然后一个线程调用object.wati(),另一个调用object.notify(),且wait先执行。
  • 先看一段代码和结果
/**
 * wait和notify的基本用法
 * 1. 代码的执行顺序
 * 2. wait释放锁
 *
 * @author yiren
 */
public class Wait {
    private final static Object object = new Object();
    static class ThreadOne extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                try {
                    System.out.println(Thread.currentThread().getName() + " in run before wait");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " in run after wait");
            }
        }
    }
    static class ThreadTwo extends Thread {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println(Thread.currentThread().getName() + " in run before notify");
                object.notify();
                System.out.println(Thread.currentThread().getName() + " in run after notify");
            }
        }
    }
    public static void main(String[] args) throws InterruptedException {
        ThreadOne threadOne = new ThreadOne();
        ThreadTwo threadTwo = new ThreadTwo();
        threadOne.start();
        Thread.sleep(100);
        threadTwo.start();
    }
}
复制代码
Thread-0 in run before wait
Thread-1 in run before notify
Thread-1 in run after notify
Thread-0 in run after wait
Process finished with exit code 0
复制代码
  • 执行顺序如上结果,执行解释如下
  • Thread-0先进入执行,然后wait()进入等待唤醒的WAITING状态,并释放锁
  • Thread-1后进入执行,发现加锁了,然后等待Thread-0释放锁过后调用notify()通知Thread-0不用等了,不过此时由于Thread-1持有了object的锁,所以Thread-1先执行完毕后释放锁,然后Thread-0再拿到锁,把wait()后面的代码执行完毕。

1.2 wait-notifyAll 用法

  • 创建三个线程,两个线程wait,然后用第三个线程调用notifyAll唤醒
  • 代码和即如果如下
/**
 * 三个线程 2个被wait阻塞,另一个来唤醒他们
 *
 * @author yiren
 */
public class WaitNotifyAll implements Runnable {
    private static final Object objectOne = new Object();
    @Override
    public void run() {
        synchronized (objectOne) {
            Thread currentThread = Thread.currentThread();
            System.out.println(currentThread.getName() + " in run before wait, state is " + currentThread.getState());
            try {
                objectOne.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(currentThread.getName() + " in run after wait, state is " + currentThread.getState());
        }
    }
    public static void main(String[] args) throws InterruptedException {
        WaitNotifyAll waitNotifyAll = new WaitNotifyAll();
        Thread threadOne = new Thread(waitNotifyAll,"thread-one");
        Thread threadTwo = new Thread(waitNotifyAll,"thread-two");
        Thread threadThree = new Thread(() -> {
            synchronized (objectOne) {
                Thread currentThread = Thread.currentThread();
                System.out.println(currentThread.getName() + " in run before notifyAll, state is " + currentThread.getState());
                objectOne.notifyAll();
                System.out.println(currentThread.getName() + " in run after notifyAll, state is " + currentThread.getState());
            }
        }, "thread-three");
        threadOne.start();
        threadTwo.start();
        Thread.sleep(200);
        threadThree.start();
    }
}
复制代码
thread-one in run before wait, state is RUNNABLE
thread-two in run before wait, state is RUNNABLE
thread-three in run before notifyAll, state is RUNNABLE
thread-three in run after notifyAll, state is RUNNABLE
thread-two in run after wait, state is RUNNABLE
thread-one in run after wait, state is RUNNABLE
Process finished with exit code 0
复制代码
  • 线程1和2分别先后进入到WAITING状态后释放锁,
  • 线程3进入run方法后调用notifyAll唤醒,执行完毕run方法 释放锁,线程1和2抢占锁然后执行wait方法后面的代码。

1.3 wait释放锁

  • 我们在使用wait的时候,它只会释放它的那把锁,代码入下:
/**
 * 证明wait 只释放当前的那把锁
 *
 * @author yiren
 */
public class WaitNotifyReleaseOwnMonitor {
    private static final Object objectOne = new Object();
    private static final Object objectTwo = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread threadOne = new Thread(() -> {
            synchronized (objectOne) {
                System.out.println(Thread.currentThread().getName() + " got objectOne lock ");
                synchronized (objectTwo) {
                    System.out.println(Thread.currentThread().getName() + " got objectTwo lock ");
                    try {
                        System.out.println(Thread.currentThread().getName() + " release objectOne lock ");
                        objectOne.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        Thread threadTwo = new Thread(() -> {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (objectOne) {
                System.out.println(Thread.currentThread().getName() + " got lock objectOne");
                synchronized (objectTwo) {
                    System.out.println(Thread.currentThread().getName() + " got lock objectTwo");
                }
            }
        });
        threadOne.start();
        threadTwo.start();
    }
}
复制代码
Thread-0 got objectOne lock 
Thread-0 got objectTwo lock 
Thread-0 release objectOne lock 
Thread-1 got lock objectOne
复制代码
  • 注意上面的运行并没有介绍。因为两个线程都还没有执行完毕。

1.4 wait、notify、notifyAll特点和性质

  • 使用时必须先拥有monitor,也就是获取到这个对象的锁
  • notify只唤醒一个,取决于JVM。notifyAll则是唤醒全部。
  • 都是数据Object的对象的方法,且都是final修饰的native方法。
  • 类似功能的有一个Condition对象
  • 如果线程同时持有多把锁一定要注意释放顺序,不然容易产生死锁。

1.5 生产者消费者模式实现

/**
 * 用wait notify实现生产者消费者模式
 * @author yiren
 */
public class ProducerConsumer {
    public static void main(String[] args) {
        EventStorage storage = new EventStorage();
        Thread producerThread = new Thread(new Producer(storage));
        Thread consumerThread = new Thread(new Consumer(storage));
        producerThread.start();
        consumerThread.start();
    }
    private static class Producer implements Runnable{
        EventStorage storage;
        public Producer(EventStorage storage) {
            this.storage = storage;
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.put();
            }
        }
    }
    private static class Consumer implements Runnable{
        EventStorage storage;
        public Consumer(EventStorage storage) {
            this.storage = storage;
        }
        @Override
        public void run() {
            for (int i = 0; i < 100; i++) {
                storage.take();
            }
        }
    }
    private static class EventStorage {
        private int maxSize;
        private LinkedList<LocalDateTime> storage;
        public EventStorage() {
            maxSize = 10;
            storage = new LinkedList<>();
        }
        public synchronized void put() {
            while (storage.size() == maxSize) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            storage.add(LocalDateTime.now());
            System.out.println("storage has " + storage.size() + " product(s).");
            notify();
        }
        public synchronized void take() {
            while (storage.size() == 0) {
                try {
                    wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("get date " + storage.poll() + ", storage has " + storage.size() + " product(s).");
            notify();
        }
    }
}
复制代码
storage has 1 product(s).
storage has 2 product(s).
storage has 3 product(s).
storage has 4 product(s).
storage has 5 product(s).
storage has 6 product(s).
storage has 7 product(s).
storage has 8 product(s).
storage has 9 product(s).
storage has 10 product(s).
get date 2020-02-11T15:46:43.554, storage has 9 product(s).
get date 2020-02-11T15:46:43.554, storage has 8 product(s).
get date 2020-02-11T15:46:43.554, storage has 7 product(s).
get date 2020-02-11T15:46:43.554, storage has 6 product(s).
get date 2020-02-11T15:46:43.554, storage has 5 product(s).
get date 2020-02-11T15:46:43.554, storage has 4 product(s).
get date 2020-02-11T15:46:43.554, storage has 3 product(s).
get date 2020-02-11T15:46:43.554, storage has 2 product(s).
get date 2020-02-11T15:46:43.554, storage has 1 product(s).
get date 2020-02-11T15:46:43.555, storage has 0 product(s).
storage has 1 product(s).
storage has 2 product(s).
storage has 3 product(s).
storage has 4 product(s).
get date 2020-02-11T15:46:43.555, storage has 3 product(s).
get date 2020-02-11T15:46:43.555, storage has 2 product(s).
get date 2020-02-11T15:46:43.555, storage has 1 product(s).
get date 2020-02-11T15:46:43.555, storage has 0 product(s).
复制代码

1.6 常见面试问题

  • 两个线程交替打印0-100的奇偶数
  1. 用synchronized来实现
/**
 * 两个线程交替打印0-100
 * @author yiren
 */
public class OddEvenBySync {
    /*
     两个线程
        1. 一个处理偶数(Even),另一个处理奇数(Odd) 用位运算来实现判断
        2. 用synchronized 来实现
     */
    private static volatile int count = 0;
    private static final Object lock = new Object();
    public static void main(String[] args) {
        Thread threadEven = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // if (count % 2 == 0) {
                    if (0 == (count & 1)) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "thread-even");
        Thread threadOdd = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // if (count % 2 == 0) {
                    if (1 == (count & 1)) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "thread-odd");
        threadEven.start();
        threadOdd.start();
    }
}
复制代码
  1. 用wait-notify实现
/**
 * 使用wait-notify 实现奇偶打印
 * @author yiren
 */
public class OddEvenByWaitNotify {
    private static final Object lock = new Object();
    private static int count = 0;
    private static final int MAX_COUNT = 100;
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                while (count <= MAX_COUNT ) {
                    synchronized (lock) {
                        try {
                            System.out.println(Thread.currentThread().getName() + ": " + count++);
                            lock.notify();
                            // 如果任务还没结束 就让出锁 自己休眠
                            lock.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
  • 手写生产者消费者设计模式 (前面有代码)
  • 为什么wait()需要在同步代码块中实现,而sleep不需要
  1. wait设计是针对多个线程的,如果多个线程运行的时候,在执行wait前就切换到了另外一个线程,恰好把notify执行掉了,那么就会形成死锁。
  2. 而sleep则是针对单个线程本身,不涉及到其他线程。
  • 为什么线程通信的方法wait(),notify()和notifyAll()被定义在Object类里面?而Sleep定义在Thread类里面?
  1. wait(),notify(),notifyAll()属于锁级别的操作,而锁一般是针对某个对象的,所以就定义在了Object中。每一个对象,在对象头中,都是有几位来表示当前锁的状态的,所以这个锁是绑定到某个对象上面,而并不是线程中。
  2. 如果把这些方法放在了Thread中,那么如果一个线程中持有了多把锁,就没有办法灵活的实现这样的多锁逻辑,也会增加编程难度。
  • wait()方法属于Object对象,那如果调用Thread.wait方法会怎样?
  • 对于Thread类特别特殊,因为在JVM中,线程在退出的现实中,它会自己去执行notify,这样会使我们设计的程序受到干扰。
  • 如何选择用notify和notifyAll
  • 主要考虑是我们需要唤醒的是单个线程还是多个线程
  • notifyAll之后所有的线程都会再次抢夺锁,如果某线程抢夺锁失败怎么办?
  • notifyAll线程执行完同步块中代码后,其他线程会同时竞争这把锁,只有一个线程会竞争成功,其他线程会进入到WAITING状态,等待竞争成功的这个线程执行结束再次竞争锁
  • 能不能用suspend()和resume()来阻塞线程?为什么?
  • Java官方是不推荐使用suspend来阻塞线程的,并且两个方法以及注明了过时,推荐使用wait-notify来实现

2. Sleep方法详解

  • 让线程在预期的时间执行,其他事件不要占用CPU资源
  • wait()会释放锁,但是sleep()方法不释放锁,包括synchronizedlock

2.1 sleep不释放锁

  1. synchronized
/**
 * sleep不释放锁
 * @author yiren
 */
public class SleepDontReleaseMonitor {
    public static void main(String[] args) {
        final Object object = new Object();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    System.out.println(Thread.currentThread().getName() + " into synchronized !");
                    try {
                        Thread.sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + " out to synchronized !");
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
Thread-0 into synchronized !
Thread-0 out to synchronized !
Thread-1 into synchronized !
Thread-1 out to synchronized !
Process finished with exit code 0
复制代码
  1. Lock
public class SleepDontReleaseLock {
    private static final Lock LOCK = new ReentrantLock();
    public static void main(String[] args) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                LOCK.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " into LOCK !");
                    Thread.sleep(3000);
                    System.out.println(Thread.currentThread().getName() + " out to LOCK !");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    LOCK.unlock();
                }
            }
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
    }
}
复制代码
Thread-0 into LOCK !
Thread-0 out to LOCK !
Thread-1 into LOCK !
Thread-1 out to LOCK !
Process finished with exit code 0
复制代码

2.2 响应中断

  • 在调用时,会抛出InterruptedException,并且清除中断状态
/**
 * sleep响应中断案例
 * Thread.sleep()
 * TimeUnit.SECONDS.sleep()
 *
 * @author yiren
 */
public class SleepInterrupted {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName() + ": " + LocalDateTime.now());
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    System.out.println(Thread.currentThread().getName() + ": was interrupted!");
                }
            }
        });
        thread.start();
        Thread.sleep(3500);
        thread.interrupt();
    }
}
复制代码
  • sleep(time)可以通过TimeUnit.时间单位.sleep(time)调用;此方法优于Thread.sleep(time)我们可以看下它的源码,它做了一个大于零的判断,以免传入负数,而Thread.sleep(time)中如果传入负数则会报IllegalArgumentException错误。
public void sleep(long timeout) throws InterruptedException {
        if (timeout > 0) {
            long ms = toMillis(timeout);
            int ns = excessNanos(timeout, ms);
            Thread.sleep(ms, ns);
        }
    }
复制代码

2.3 一句话总结

  • sleep(time)方法可以让线程进入到WAITING状态,并停止占用CPU资源,但是不释放锁,直到规定事件后再执行,休眠期间如果被中断,会抛出异常并清除中断状态。

2.4 常见面试问题

  • wait/notify、sleep异同
  • 方法属于哪个对象?线程状态怎么切换。
  • 相同:都进入阻塞,都响应中断
  • 不同:wait/notify需要同步块,sleep不需要;wait释放锁,sleep不释放;wait可不指定时间,sleep必须指定;所属类不同

3. join方法详解

3.1 作用及用法

  • 作用:新线程加入,所以要等待它执行完再出发
  • 用法:main等待thread1、thread2等线程执行完毕
  1. 普通用法
/**
 * 普通用法
 * @author yiren
 */
public class JoinSimple {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        Thread thread2 = new Thread(runnable);
        thread1.start();
        thread2.start();
        System.out.println("start to wait child threads.");
        thread1.join();
        thread2.join();
        System.out.println("all threads run completed!");
    }
}
复制代码
start to wait child threads.
Thread-0 was finished!
Thread-1 was finished!
all threads run completed!
Process finished with exit code 0
复制代码
  • 如果两个线程不join的话就会先打印最后一句话。
  1. 中断
  • thread.join()响应的中断是执行join方法的这个线程的中断 而不是thread,就如下方代码,中断的是主线程。
/**
 * 响应中断
 * @author yiren
 */
public class JoinInterrupt {
    public static void main(String[] args) {
        final Thread mainThread = Thread.currentThread();
        Runnable runnable = () -> {
            try {
                mainThread.interrupt();
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        thread1.start();
        System.out.println("start to wait child thread.");
        try {
            thread1.join();
        } catch (InterruptedException e) {
            // 实际是主线程中断
            System.out.println(Thread.currentThread().getName() + " was interrupted!");
            e.printStackTrace();
        }
    }
}
复制代码
start to wait child thread.
main was interrupted!
java.lang.InterruptedException
  at java.lang.Object.wait(Native Method)
  at java.lang.Thread.join(Thread.java:1252)
  at java.lang.Thread.join(Thread.java:1326)
  at com.imyiren.concurrency.thread.method.JoinInterrupt.main(JoinInterrupt.java:25)
Thread-0 was finished!
Process finished with exit code 0
复制代码
  1. join期间线程状态
/**
 * join发生后 主线程的状态
 * @author yiren
 */
public class JoinState {
    public static void main(String[] args) {
        Thread mainThread = Thread.currentThread();
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.SECONDS.sleep(3);
                System.out.println("main thread state: " + mainThread.getState());
                System.out.println(Thread.currentThread().getName() + " finished");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        try {
            System.out.println("waiting child thread");
            thread.join();
            System.out.println("completed child thread");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
复制代码
waiting child thread
main thread state: WAITING
Thread-0 finished
completed child thread
Process finished with exit code 0
复制代码

3.2 join源码分析

public final void join() throws InterruptedException {
        join(0);
    }
    
    public final synchronized void join(long millis) throws InterruptedException {
        long base = System.currentTimeMillis();
        long now = 0;
        if (millis < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }
        if (millis == 0) {
            while (isAlive()) {
                wait(0);
            }
        } else {
            while (isAlive()) {
                long delay = millis - now;
                if (delay <= 0) {
                    break;
                }
                wait(delay);
                now = System.currentTimeMillis() - base;
            }
        }
    }
复制代码
- `join(0)`是代表无限期等待
- 它的根本方法就是调用的`wait(time)`
- 但是没有notify?其实是JVM的Thread执行完毕会自动执行一次notifyAll。
- 既然知道它是通过wait-notify实现的,那么我们可以写一下等价的代码:
复制代码
/**
 * 自己实现 等价代码
 * @author yiren
 */
public class JoinImplements {
    public static void main(String[] args) throws InterruptedException {
        Runnable runnable = () -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + " was finished!");
        };
        Thread thread1 = new Thread(runnable);
        thread1.start();
        System.out.println("start to wait child threads.");
        // thread1.join(); // 等价于下方代码
        synchronized (thread1) {
            thread1.wait();
        }
        System.out.println("all threads run completed!");
    }
}
复制代码

3.3 常见面试题

  • 在join期间线程会处于那种状态?
  • WAITING

4. yield方法详解

  • 释放当前CPU占用,状态依旧是RUNNABLE
  • JVM不保证遵循yield,如CPU资源不紧张,极端点没有线程使用,即使调用yield也有可能不释放CPU资源
  • 与sleep的区别:是否可以随时再次被调度

5. Thread.currentThread()方法

  • 主要是返回当前线程的引用。
/**
 * 打印main thread-0 thread-1
 * @author yiren
 */
public class CurrentThread {
    public static void main(String[] args) {
        Runnable runnable = () -> System.out.println(Thread.currentThread().getName());
        // 主线程直接调用函数
        runnable.run();
        new Thread(runnable).start();
        new Thread(runnable).start();
    }
}
复制代码

6. start run 方法 和 stop suspend resume 方法

7. 面试常见问题

  • 为什么线程通信的方法wait(),notify()和notifyAl()被定义在Object类里面?而sleep却定义在Thread类中
  • 用三种方法实现生产者模式
  • join和sleep和wait期间线程的状态分别是什么?为什么?


目录
相关文章
|
5天前
|
JavaScript 前端开发
`Object.create()` 方法的参数
【10月更文挑战第29天】`Object.create()` 方法的参数提供了多种创建对象和控制对象属性及继承关系的方式,开发人员可以根据具体的需求灵活运用,以实现更高效、更符合设计要求的对象创建和继承机制。
|
3天前
|
存储 Java 程序员
Java基础的灵魂——Object类方法详解(社招面试不踩坑)
本文介绍了Java中`Object`类的几个重要方法,包括`toString`、`equals`、`hashCode`、`finalize`、`clone`、`getClass`、`notify`和`wait`。这些方法是面试中的常考点,掌握它们有助于理解Java对象的行为和实现多线程编程。作者通过具体示例和应用场景,详细解析了每个方法的作用和重写技巧,帮助读者更好地应对面试和技术开发。
28 4
|
5天前
|
设计模式
在实际开发中,什么时候应该使用 `new` 关键字,什么时候应该使用 `Object.create()` 方法?
【10月更文挑战第29天】`new` 关键字适用于创建具有特定类型和初始化逻辑的对象实例,以及实现基于原型链的继承;而 `Object.create()` 方法则适用于基于现有对象创建相似对象、避免构造函数的副作用、创建具有特定原型链的对象等场景。在实际开发中,需要根据具体的需求和设计模式来选择合适的方法来创建对象,以实现更高效、更灵活的代码结构。
|
23天前
|
Java 索引
Object有哪些常用方法
掌握这些方法不仅能够帮助你编写出更加健壮和高效的Java代码,还能加深对面向对象编程概念的理解。在实际开发中,合理利用 `Object`类提供的方法能够有效提升代码的可读性、可维护性和性能。
30 0
|
23天前
|
JavaScript 前端开发 大数据
在JavaScript中,Object.assign()方法或展开语法(...)来合并对象,Object.freeze()方法来冻结对象,防止对象被修改
在JavaScript中,Object.assign()方法或展开语法(...)来合并对象,Object.freeze()方法来冻结对象,防止对象被修改
13 0
|
1月前
|
Java
Java Object 类详解
在 Java 中,`Object` 类是所有类的根类,每个 Java 类都直接或间接继承自 `Object`。作为所有类的超类,`Object` 定义了若干基本方法,如 `equals`、`hashCode`、`toString` 等,这些方法在所有对象中均可使用。通过重写这些方法,可以实现基于内容的比较、生成有意义的字符串表示以及确保哈希码的一致性。此外,`Object` 还提供了 `clone`、`getClass`、`notify`、`notifyAll` 和 `wait` 等方法,支持对象克隆、反射机制及线程同步。理解和重写这些方法有助于提升 Java 代码的可读性和可维护性。
|
6月前
|
Java
Java Object 类
5月更文挑战第16天
|
3月前
|
Java
【Java基础面试二十】、介绍一下Object类中的方法
这篇文章介绍了Java中Object类的常用方法,包括`getClass()`、`equals()`、`hashCode()`、`toString()`、`wait()`、`notify()`、`notifyAll()`和`clone()`,并提到了不推荐使用的`finalize()`方法。
【Java基础面试二十】、介绍一下Object类中的方法
|
2月前
|
Python
类与面向对象编程(Object-Oriented Programming, OOP)
类与面向对象编程(Object-Oriented Programming, OOP)
|
3月前
|
前端开发 Java 编译器
【前端学java】java中的Object类和前端中的Object有什么区别(9)
【8月更文挑战第10天】java中的Object类和前端中的Object有什么区别
40 0
【前端学java】java中的Object类和前端中的Object有什么区别(9)
下一篇
无影云桌面