线程阻塞状态实例分析

有三种方法可以暂停Threads执行:
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("儿子买烟回来了");
	}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值