本文共 1178 字,大约阅读时间需要 3 分钟。
join方法: 当某个线程要等待另一个线程执行结束后才能继续执行时,使用join方法。
public class DinnerThread { public static void main(String[] args){ DinnerThread thread = new DinnerThread(); Dinner fatherThread = thread.new Dinner(); Thread myThread = new Thread(fatherThread); myThread.start(); } public class Dinner implements Runnable { public void run() { System.out.println("去饭店吃饭"); System.out.println("点完菜让饭店做菜:"); Thread restaurantThread = new Thread(new RestaurantThread()); restaurantThread.start(); try { restaurantThread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("开始吃饭"); } } public class RestaurantThread implements Runnable{ public void run() { System.out.println("饭店开始做菜"); for(int i=0;i<10;i++){ System.out.println("饭店做菜("+(i+1)+")..."); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println("饭店上菜"); } }}
打印结果如下:
去饭店吃饭
点完菜让饭店做菜:饭店开始做菜饭店做菜(1)...饭店做菜(2)...饭店做菜(3)...饭店做菜(4)...饭店做菜(5)...饭店做菜(6)...饭店做菜(7)...饭店做菜(8)...饭店做菜(9)...饭店做菜(10)...饭店上菜开始吃饭转载地址:http://abtaa.baihongyu.com/