曾经被问过,Object中的方法。当时没有回答好。
public final native Class<?> getClass()
public native int hashCode()
public boolean equals(Object obj)
protected native Object clone() throws CloneNotSupportedException
public String toString()
public final native void notify()
public final native void notifyAll()
public final native void wait(long timeout) throws InterruptedException
public final void wait(long timeout, int nanos) throws InterruptedException
public final void wait() throws InterruptedException
protected void finalize() throws Throwable { }
其实从刚接触Java不久,记住掉wait和notify,但一直没有动手写过demo,所以认识模糊。
在java中,线程间的通信可以使用wait、notify、notifyAll来进行控制。从名字就可以看出来这3个方法都是跟多线程相关的,但是可能让你感到吃惊的是:这3个方法并不是Thread类或者是Runnable接口的方法,而是Object类的3个本地方法。
这里实现一个生产者-消费者模式。
class Producer implements Runnable {
volatile List<Integer> msgList;
public Producer(List<Integer> msgList) {
this.msgList = msgList;
}
@Override
public void run() {
try {
while (true) {
Thread.sleep(1000);
synchronized (msgList) {
msgList.add(ThreadLocalRandom.current().nextInt(50));
msgList.notify();
//这里只能是notify而不能是notifyAll,否则remove(0)会报java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
//如果是notifyAll,则需要用循环表示
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Consumer implements Runnable {
volatile List<Integer> msgList;
public Consumer(List<Integer> msgList) {
this.msgList = msgList;
}
@Override
public void run() {
while (true) {
synchronized (msgList) {
if (msgList.isEmpty()) {
try {
msgList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/* while (msgList.isEmpty()) {
try {
msgList.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}*/
System.out.println(msgList.remove(0));
}
}
}
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
Producer producer = new Producer(list);
new Thread(producer).start();
Consumer consumer1 = new Consumer(list);
Consumer consumer2 = new Consumer(list);
Consumer consumer3 = new Consumer(list);
new Thread(consumer1).start();
new Thread(consumer2).start();
new Thread(consumer3).start();
}
}
网友评论