java线程唤醒机制
/* 线程唤醒机制的作用: 使线程按照一定的顺序执行
* wait()是Object类的方法,调用对象的wait()方法导致当前线程放弃对象的锁(线程暂停执行),
* 进入对象的等待池(wait pool),OS会将执行时间分配给其它线程,同样也是进入阻塞态。
* 只有调用对象的notify()方法(或notifyAll()方法)时才能唤醒等待池中的线程进入等锁池(lock pool),
* 如果线程重新获得对象的锁就可以进入就绪状态。
* notify():唤醒一个处于等待状态的线程,在调用此方法的时候,并不能确切的唤醒某一个等待状态的线程,
* 而是由JVM确定唤醒哪个线程,而且与优先级无关;
* notityAll():唤醒所有处于等待状态的线程,该方法并不是将对象的锁给所有线程,
* 而是让它们竞争,只有获得锁的线程才能进入就绪状态;
*
*
* 多线程之间的通信
* notifyAll()方法是唤醒所有的线程
* 1.在同步代码块中,用哪个对象锁,就用哪个对象调用wait方法
* 2.为什么wait方法和notify()方法定义在Object这类中?
* 因为锁对象可以是任意对象,Object是所有类的基类,所以wait方法和notify方法需要定义在Object这个类中
* 3.sleep方法和wait方法的区别?
* a.sleep方法必须传入参数,参数就是时间,时间到了自动醒来
* wait方法可以传入参数也可以不传入参数,传入参数就是在参数的时间结束后等待,不传入参数就是直接等待
* b.sleep方法在同步代码块中不释放锁
* wait方法在同步代码块中,释放锁
*/
public class Wait {
public static void main(String[] args) {
// TODO Auto-generated method stub
Printer5 p = new Printer5();
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
p.printer1();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
p.pirnter2();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread(){
@Override
public void run() {
// TODO Auto-generated method stub
while(true){
try {
p.pirnter3();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
//等待唤醒机制
class Printer5{
private int flag = 1;
public void printer1() throws InterruptedException{
synchronized (this) { //同步代码块,锁机制,锁对象可以是任意的
while(flag != 1){
this.wait(); //当前线程等待
}
System.out.print("k"); //锁对象不能用匿名对象,因为匿名对象不是同一个对象,就意味着不是同一把锁
System.out.print("l");
System.out.print("z");
System.out.println("\r\n");
flag = 2;
// this.notify();
this.notifyAll();
}
}
public void pirnter2() throws InterruptedException{
synchronized (this) {
while(flag != 2){
this.wait();
}
System.out.print("x");
System.out.print("y");
System.out.print("z");
System.out.println("\r\n");
flag = 3;
// this.notify();
this.notifyAll();
}
}
public void pirnter3() throws InterruptedException{
synchronized (this) {
while(flag != 3){ //线程3在此等待,if语句是在哪里等待,就在那里起来
this.wait(); //while循环是循环判断,每次都会判断标记
}
System.out.print("i");
System.out.print("t");
System.out.print("h");
System.out.print("e");
System.out.println("\r\n");
flag = 1;
// this.notify();
this.notifyAll();
}
}
}