1.线程状态概述
-
6中状态
-
新建状态
new
-
阻塞状态
Blocked
-
运行状态
Runnable
-
死亡状态
Teminated
-
休眠(计时等待)状态
Timed Waiting
-
无线等待状态
Waiting
2.等待wait()
唤醒notify()
锁对象.wait(); 上锁
锁对象.notify(); 解锁
public class DemoWaiting {
public static void main(String[] args) {
//创建锁对象
Object obj = new Object();
Thread guke = new Thread() {
@Override
public void run() {
while (true) {
System.out.println("顾客:老板,来五个包子!");
synchronized (obj) { //吃包子和做包子不能同时进行,所以用synchronized(锁对象)
try {//顾客吃包子要等老板做包子以后,所以进入Waiting状态,等待老板notify唤醒
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("顾客:谢谢老板,开吃了!");//唤醒之后的顾客开始吃包子
System.out.println("=======================================================");
}
}
};
Thread laoban = new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (obj) {//吃包子和做包子不能同时进行,所以用synchronized(锁对象) synchronized (obj) {//吃包子和做包子不能同时进行,所以用synchronized(锁对象)
System.out.println("5s之后");
System.out.println("老板:包子好了!");
obj.notify();//做好包子以后用notify唤醒顾客,吃包子
}
}
}
};
guke.start();
laoban.start();
}
}