有三种方法可以暂停Threads执行:
1.sleep方法:sleep时别的线程也不可以访问锁定对象。
2.yield方法:让出cpu的使用权,从运行态直接进入就绪状态。让cpu重新挑选哪一个线程进入运行状态。
3.join方法:当某一个线程等待另一个线程执行结束后,才继续执行时,使用join方法。使调用该方法的线程在此之前执行完毕,也就是等待调用该方法的线程执行完毕后再往下继续执行。
1.sleep方法:sleep时别的线程也不可以访问锁定对象。
2.yield方法:让出cpu的使用权,从运行态直接进入就绪状态。让cpu重新挑选哪一个线程进入运行状态。
3.join方法:当某一个线程等待另一个线程执行结束后,才继续执行时,使用join方法。使调用该方法的线程在此之前执行完毕,也就是等待调用该方法的线程执行完毕后再往下继续执行。
public class Test2 {
public static void main(String[] args) {
System.out.println("爸爸和儿子买烟的故事");
Thread father=new Thread(new FatherThread());
father.start();
}
}
class FatherThread implements Runnable{
public void run(){
System.out.println("爸爸想抽烟,发现烟抽完了");
System.out.println("爸爸让儿子去买烟");
Thread son=new Thread(new SonThread());
son.start();
System.out.println("爸爸等儿子买烟回来");
try{
son.join();
}catch(InterruptedException e){
e.printStackTrace();
System.out.println("爸爸出门去找儿子");
System.exit(1);
}
System.out.println("爸爸高兴的接过烟开始抽,并把钱给了儿子");
}
}
class SonThread implements Runnable{
public void run(){
System.out.println("儿子出去买烟");
System.out.println("儿子买烟需要10分钟");
try{
for(int i=1;i<=10;i++){
System.out.println("第"+i+"分钟");
Thread.sleep(1000);
}
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("儿子买烟回来了");
}
}