Print类
public class Print implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + "线程开始运行"); for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()); } System.out.println(Thread.currentThread().getName() + "线程结束运行"); }}
Racer类
public class Racer implements Runnable { public void run() { if (Thread.currentThread().getName().equals("兔子")) { for (int i = 0; i <= 50; i += 3) { if (i % 15 == 0 && i != 0) { try { System.out.println("兔子开始休息"); Thread.sleep((int) (Math.random() * 15 + 5) * 1000); } catch (InterruptedException e) { e.printStackTrace(); } } else { try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "跑了" + i + "米"); } catch (InterruptedException e) { e.printStackTrace(); } } } System.out.println("兔子跑完50米,赢了!"); } else { for (int j = 0; j <= 50; j++) { try { Thread.sleep(1000); System.out.println(Thread.currentThread().getName() + "跑了" + j + "米"); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("乌龟跑完50米,赢了!"); } System.exit(0); }}
Main函数
public class Test { public static void main(String[] args) { print(); run(); } public static void print() { Runnable task = new Print(); Thread t1 = new Thread(task, "B"); t1.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); } Thread t2 = new Thread(task, "A"); t2.start(); Thread t3 = new Thread(task, "C"); t3.start(); try { t2.join(); t3.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public static void run() { Runnable task = new Racer(); Thread t1 = new Thread(task, "兔子"); Thread t2 = new Thread(task, "乌龟"); t1.start(); t2.start(); }}