线程共六种状态,它们之间可以相互转换:
多个线程一起抢夺cpu执行权,抢到进入RUNNABLE状态,没抢到进入阻塞状态BLOCKED。RUNNABLE和BLOCKED之间可以相互转换。
阻塞状态具有CPU的执行资格,而休眠和无限等待状态都是主动放弃CPU的执行资格。
运行状态遇到sleep(long)和wait(long)进入休眠状态,计时等待;而wait()进入无限等待。
Waiting无限等待状态
等待唤醒案例:线程之间的通信
创建一个顾客线程(消费者):告知老板要的包子的种类和数量,调用wait方法,放弃cpu的执行,进入到WAITING状态(无限等待)
创建一个老板线程(生产者):花了5秒做包子,做好包子之后,调用notify方法,唤醒顾客吃包子
注意:
顾客和老板线程必须使用同步代码块包裹起来,保证等待和唤醒只能有一个在执行
同步使用的锁对象必须保证唯—
只有锁对象才能调用wait和notify方法
Obejct类中的方法
void wait() 在其他线程调用此对象的notify()方法或notifyAll()方法前,导致当前线程等待。
void notify() 唤醒在此对象监视器上等待的单个线程。会继续执行wait方法之后的代码。
public class waiting {
public static void main(String[] args) {
Object obj=new Object();
//顾客线程
new Thread(){
public void run(){
while(true){
synchronized (obj){
System.out.println("买");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("吃");
System.out.println("-----------------");
}
}
}
}.start();
//老板线程
new Thread(){
public void run(){
while (true){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//保证等待和唤醒的进程只能有一个执行,使用同步技术
synchronized (obj){
System.out.println("做好了");
obj.notify();
}
}
}
}.start();
}
}
进入到Timelwaiting(计时等待)有两种方式 1.使用sleep(long m)方法,在毫秒值结束之后,线程睡醒进入到Runnable/BLocked状态 2.使用wait(Long m)方法, wait方法如果在毫秒值结束之后,还没有被notify唤醒,就会自动醒来,线程睡醒进入到Runnable/BLocked状态 唤醒的方法: void notify()唤醒在此对象监视器上等待的单个线程。(随机唤醒一个) void notifyAll()唤醒在此对象监视器上等待的所有线程。
public class waiting {
public static void main(String[] args) {
Object obj=new Object();
//顾客1线程
new Thread(){
public void run(){
while(true){
synchronized (obj){
System.out.println("1买");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1吃");
System.out.println("-----------------");
}
}
}
}.start();
//顾客二
new Thread(){
public void run(){
while(true){
synchronized (obj){
System.out.println("2买");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2吃");
System.out.println("-----------------");
}
}
}
}.start();
//老板线程
new Thread(){
public void run(){
while (true){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//保证等待和唤醒的进程只能有一个执行,使用同步技术
synchronized (obj){
System.out.println("做好了");
//obj.notify();//如果有多个等待线程,随机唤醒一个
obj.notifyAll();//唤醒所有等待线程
}
}
}
}.start();
}
}