面试题

1、Automic与volatile的区别
2、sleep与wait的区别,notify与notifyall的区别

  • sleep是Thread的静态方法,wait是Object的方法,任何对象实例都能调用。
  • sleep不会释放锁,它也不需要占用锁。wait会释放锁,但调用它的前提是当前线程占有锁(即代码要在synchronized中)。
  • 它们都可以被interrupted方法中断。
    notify与notifyall区别
    `package com.lagou.notify_all;

public class TestNotifyNotifyAll {

private static Object obj = new Object();

public static void main(String[] args) {

    //测试 RunnableImplA wait()
    Thread t1 = new Thread(new RunnableImplA(obj));
    Thread t2 = new Thread(new RunnableImplA(obj));
    t1.start();
    t2.start();

    //RunnableImplB notify()
    Thread t3 = new Thread(new RunnableImplB(obj));

// t3.start();

// //RunnableImplC notifyAll()
Thread t4 = new Thread(new RunnableImplC(obj));
t4.start();
}

}

class RunnableImplA implements Runnable {

private Object obj;

public RunnableImplA(Object obj) {
    this.obj = obj;
}

public void run() {
    System.out.println("run on RunnableImplA");
    synchronized (obj) {
        System.out.println("obj to wait on RunnableImplA");
        try {
            obj.wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("obj continue to run on RunnableImplA");
    }
}

}

class RunnableImplB implements Runnable {

private Object obj;

public RunnableImplB(Object obj) {
    this.obj = obj;
}

public void run() {
    System.out.println("run on RunnableImplB");
    System.out.println("睡眠3秒...");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    synchronized (obj) {
        System.out.println("notify obj on RunnableImplB");
        obj.notify();
    }
}

}

class RunnableImplC implements Runnable {

private Object obj;

public RunnableImplC(Object obj) {
    this.obj = obj;
}

public void run() {
    System.out.println("run on RunnableImplC");
    System.out.println("睡眠3秒...");
    try {
        Thread.sleep(3000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    synchronized (obj) {
        System.out.println("notifyAll obj on RunnableImplC");
        obj.notifyAll();
    }
}

}
`

原文地址:https://www.cnblogs.com/kukudetent/p/13440580.html