主要的有getClass,hashCode,equals,clone,toString,notify,notifyAll,wait
package org.example;
public class objectTest extends Object implements Cloneable{
public static void main(String[] args) {
// getClass()方法用于获取当前对象的类信息,并返回一个Class对象。
Object obj = new Object();
Class<?> clazz = obj.getClass();
System.out.println("Class name: " + clazz.getName());
// hashCode方法
int hashCode = obj.hashCode();
System.out.println("Hash code: " + hashCode);
// equals()方法,判断地址相同
Object obj2 = new Object();
System.out.println(obj.equals(obj2));
// clone方法,具有protected访问权限,,equals方法不相等,浅拷贝
objectTest obj3 = new objectTest();
try {
objectTest obj4 = (objectTest) obj3.clone();
System.out.println(obj3.equals(obj4));
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
// toString方法,返回对象的字符串表示形式
System.out.println(obj.toString());
}
}
clone方法,浅拷贝,要使用 clone()
方法,类必须实现 Cloneable
接口
- 浅拷贝:浅拷贝会创建一个新对象,新对象的基本数据类型属性会复制一份新的值,而引用数据类型属性则只是复制引用,即新对象和原对象的引用数据类型属性指向同一个内存地址。也就是说,修改新对象的引用数据类型属性会影响原对象,反之亦然。
- 深拷贝:深拷贝同样会创建一个新对象,新对象的所有属性,包括基本数据类型和引用数据类型,都会进行全新的复制。新对象和原对象的所有属性都指向不同的内存地址,修改新对象的任何属性都不会影响原对象,反之亦然。
当调用 clone()
方法时,会创建一个新的对象实例,新对象和原对象在内存中占据不同的地址,所以使用 Object
类默认的 equals()
方法比较原对象和克隆对象时,结果必然是 false
package org.example;
class SharedResource {
public synchronized void waitForSignal() throws InterruptedException {
System.out.println("Thread " + Thread.currentThread().getName() + " is waiting.");
wait();
System.out.println("Thread " + Thread.currentThread().getName() + " has been notified.");
}
public synchronized void sendSignal() {
System.out.println("Sending signal...");
notify();
}
}
public class ThreadCommunicationExample {
public static void main(String[] args) {
SharedResource resource = new SharedResource();
Thread waiter = new Thread(() -> {
try {
resource.waitForSignal();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread notifier = new Thread(() -> {
try {
Thread.sleep(2000);
resource.sendSignal();
} catch (InterruptedException e) {
e.printStackTrace();
}
});
waiter.start();
notifier.start();
}
}
notify()
、notifyAll()
和 wait()
方法
- 功能:这些方法用于线程间的通信。
notify()
方法用于唤醒在此对象监视器上等待的单个线程;notifyAll()
方法用于唤醒在此对象监视器上等待的所有线程;wait()
方法用于使当前线程等待,直到其他线程调用该对象的notify()
或notifyAll()
方法。