昨天没有时间写完这篇,今天补上,前面只说明了wait和notify这两个方法,这里讨论一下sleep和join,说实在的这两个方法比wait和notify简单的多.
http://blog.csdn.net/treeroot/archive/2004/11/10/175508.aspx
sleep:thread的静态方法,当前线程休眠一段时间,时间到了再恢复可运行状态,时间到了不一定就执行吧,还得竞争cpu呢.
join:这个方法其实就是特殊的wait,wait方法一般都需要别人notify(当然也可以设置超时),但是join方法就不需要别人notify了,一直等到这个线程死亡(就相当于这个线程临时前告诉那些在等它的人:你们进来吧!)
本人不是很会举例子,还是两个人公用一个卫生间吧,这回不刷牙了,改洗澡吧,总不能两个人同时洗澡吧!就算可以,这里假设不可以吧.情况时这样的:a在洗澡,b要等。
第一种情况:
b很聪明的,a洗澡可能要20分钟到1小时,我就先睡10分钟看看好了没有,没有好就再睡10分钟,最多多等10分钟而已吧.
class syn
{
public static void main(string[] args) throws exception
{
thread a=new bathing();
a.start();
//b
int time=0;
while(a.isalive()){
thread.sleep(10000);
time+=10;
system.out.println("b has waited "+time+" minutes");
}
system.out.println("b can bath now!");
}
}
class bathing extends thread
{
public void run(){
bathing();
}
private void bathing() {
system.out.println("a is bathing !");
try{thread.sleep(20000);}catch(interruptedexception e){e.printstacktrace();}
//延迟20秒看效果
system.out.println("a has bathed !");
}
};
第二种情况:
b变得更加聪明了,这样等我不是亏了,如果我10分钟敲一次门,我可能要多等10分钟,但是如果我每秒敲一次我也没法睡呀,于是想了一个高招,装了一个机关,当a出来的时候机关就会按响门铃,这样b就可以高枕无忧了。
class syn
{
public static void main(string[] args) throws exception
{
thread a=new bathing();
a.start();
//b
int time=0;
a.join();
system.out.println("b can bath now!");
}
}
class bathing extends thread
{
public void run(){
bathing();
}
private void bathing() {
system.out.println("a is bathing !");
try{thread.sleep(20000);}catch(interruptedexception e){e.printstacktrace();}
//延迟20秒看效果
system.out.println("a has bathed !");
}
};
这样只要a一洗完,b就会被唤醒,这里a并没有去notify他,但是还是间接的通知了b,当然这里也可以用wati和notify实现,不过就显得不好了。
class syn
{
public static void main(string[] args) throws exception
{
thread a=new bathing();
a.start();
//b
int time=0;
synchronized(a){a.wait();}
system.out.println("b can bath now!");
}
}
class bathing extends thread
{
public void run(){
synchronized(this){
bathing();
notify();
}
}
private void bathing() {
system.out.println("a is bathing !");
try{thread.sleep(20000);}catch(interruptedexception e){e.printstacktrace();}
//延迟20秒看效果
system.out.println("a has bathed !");
}
};
对于一般的对象就要用wait和notify了,但是对于一个线程来说,join方法有时候更加方便。
闽公网安备 35060202000074号