【0805作业】模拟接力赛跑
1 package run; 2 3 public class RunThread implements Runnable { 4 private int count; 5 6 @Override 7 public void run() { 8 // TODO Auto-generated method stub 9 while (count < 1000) { 10 running(); 11 } 12 } 13 14 synchronized public void running() { 15 16 if (count < 1000) { 17 System.out.println(Thread.currentThread().getName() + "号选手拿到了接力棒!"); 18 for (int i = 0; i < 10; i++) { 19 try { 20 Thread.sleep(100); 21 } catch (InterruptedException e) { 22 // TODO Auto-generated catch block 23 e.printStackTrace(); 24 } 25 System.out.println(Thread.currentThread().getName() + "号选手跑了" + (i+1)*10+"米"); 26 count+=10; 27 if(count==1000) { 28 System.out.println("比赛结束"); 29 } 30 } 31 } 32 } 33 }
1 package run; 2 /** 3 * 多人共跑1000米 4 * 5 */ 6 public class Main { 7 public static void main(String[] args) { 8 RunThread rt=new RunThread(); 9 Thread play1=new Thread(rt,"1"); 10 Thread play2=new Thread(rt,"2"); 11 Thread play3=new Thread(rt,"3"); 12 Thread play4=new Thread(rt,"4"); 13 14 play2.setPriority(10); 15 16 play1.start(); 17 play2.start(); 18 play3.start(); 19 play4.start(); 20 } 21 }