Java 线程中的Join、wait、notify,sleep【转】
1.wait和notify
这两个方法都是Object中的方法,放在一块是因为他们关系非常密切.
wait就是等待这个对象的同步锁,不过调用这个方法必须先获得这个对象的同步锁,就这一点很多人就搞晕了.
这里先解释一下这两个方法,然后给出一个小例子说明.
wait:等待对象的同步锁,需要获得该对象的同步锁才可以调用这个方法,否则后收到一个 IllegalMonitorStateException,这个是运行时异常.调用这个方法后,就放弃了这个同步锁了.如果不带参数的wait方法就只 有等别人唤醒了,如果带一个参数的
化就设置等待最长时间,过了这个时间即使没有人唤醒这个线程也不再等待了.
notify:唤醒在等待该对象同步锁的线程(只唤醒一个,如果有多个在等待),但是notifyAll可以唤醒所有等待的线程,注意唤醒的时在notify之前wait的线程,之后的没有效果.
这里举一个通俗的例子,两个人共有一个卫生间(每次只能一个人用),他们都要刷牙和方便,他们是这样约定的,轮流用,第一个人先刷牙,然后第二个人刷牙...
class Syn
{
public static void main(String[] args) throws Exception
{
TwoPeople.ONE.start();
TwoPeople.TWO.start();
}
}
class TwoPeople extends Thread
{
private int i=0;
static Thread ONE=new TwoPeople(1);
static Thread TWO=new TwoPeople(2);
static Object washroom=new Object();
private TwoPeople(int i){this.i=i;}
public void run(){
synchronized(washroom){
try{
if(i==1){
brush(); //1
washroom.wait(); //2
release(); //6
washroom.notify(); //7
}
else{
brush(); //3
washroom.notify(); //4
washroom.wait(); //5
release(); //8
}
}catch(InterruptedException e){e.printStackTrace();}
}
}
private void brush() {
System.out.println("People "+i+" is brushing !");
try{Thread.sleep(2000);}catch(InterruptedException e){e.printStackTrace();}
//延迟两秒看效果
System.out.println("People "+i+" has burshed !");
}
private void release(){
System.out.println("People "+i+" is releasing !");
try{Thread.sleep(2000);}catch(InterruptedException e){e.printStackTrace();}
//延迟两秒看效果
System.out.println("People "+i+" has released !");
}
};
People 1 is brushing !
People 1 has burshed !
People 2 is brushing !
People 2 has burshed !
People 1 is releasing !
People 1 has released !
People 2 is releasing !
People 2 has released !
上面的代码很简短,而且表明了执行顺序,至于join和sleep还是下次再讨论吧.
阅读(3614) | 评论(0) | 转发(0) |