Sleep
package Thread01; //sleep(): 睡眠 让调用者进入阻塞状态 public class Sleep implements Runnable{ static Thread t = null; public static void main(String[] args) { Sleep s = new Sleep(); t = new Thread(s,"银河一号"); System.out.println(t.getName()+"处于创建状态"); t.start(); } @Override public void run() { // TODO Auto-generated method stub System.out.println("银河一号开始跑步!"); try { System.out.println("银河一号进入休眠,处于阻塞状态"); Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(t.getName()+"处于就绪状态!"); } }
package Thread01; //join(); 参加 让调用进入就绪状态,让当前线程进入阻塞状态 public class join { static boolean boo = false; public static void main(String[] args) { Thread t1 = new Thread("线程1下载图片:") { public void run() { System.out.println("download:开始下载图片!"); for (int i = 0; i <= 100; i++) { System.out.println(Thread.currentThread().getName() + "正在下载:" + i + "%"); } //下载完成 boo = true; } }; Thread t2 = new Thread() { public void run() { try { //要先下载再显示 t1.join(); System.out.println("show:显示图片"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("程序中止"); } //没有下载完成 抛出没有下载完成就不能显示的异常 if(!boo) { //异常Exception 分为检查异常(Checked Exception)和非检查异常(Runtime Exception) throw new RuntimeException("还未下载完成不能显示!"); } System.out.println("显示结束!"); } };
//开启两个线程 t1.start(); t2.start(); } }