notify:
notify只会唤醒众多等待线程中的其中一个线程
用包子铺案例来演示一下
package com.thread;
/**
* @author 邓亚非
*/
public class TestNotify {
private static Object object=new Object();
public static void main(String[] args) {
// 顾客1线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
System.out.println("顾客1告诉老板要什么包子");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子已经做好了,顾客1可以去买了");
}
}
}).start();
// 顾客2线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
System.out.println("顾客2告诉老板要什么包子");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子已经做好了,顾客2可以去买了");
}
}
}).start();
// 老板线程
new Thread(new Runnable() {
@Override
public void run() {
// 5秒钟做包子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object){
System.out.println("告诉顾客包子已经做好了");
object.notify();
}
}
}).start();
}
}
测试:
notifyAll()方法会唤醒所有语句在等待的线程
我们再来模拟一下
代码:
package com.thread;
/**
* @author 邓亚非
*/
public class TestNotify {
private static Object object=new Object();
public static void main(String[] args) {
// 顾客1线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
System.out.println("顾客1告诉老板要什么包子");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子已经做好了,顾客1可以去买了");
}
}
}).start();
// 顾客2线程
new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
System.out.println("顾客2告诉老板要什么包子");
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("包子已经做好了,顾客2可以去买了");
}
}
}).start();
// 老板线程
new Thread(new Runnable() {
@Override
public void run() {
// 5秒钟做包子
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (object){
System.out.println("告诉顾客包子已经做好了");
object.notifyAll();
}
}
}).start();
}
}
测试:
通过案例你们应该明白了吧哈哈哈