Print类

  1. public class Print implements Runnable {
  2. @Override
  3. public void run() {
  4. System.out.println(Thread.currentThread().getName() + "线程开始运行");
  5. for (int i = 0; i < 5; i++) {
  6. System.out.println(Thread.currentThread().getName());
  7. }
  8. System.out.println(Thread.currentThread().getName() + "线程结束运行");
  9. }
  10. }

Racer类

  1. public class Racer implements Runnable {
  2. public void run() {
  3. if (Thread.currentThread().getName().equals("兔子")) {
  4. for (int i = 0; i <= 50; i += 3) {
  5. if (i % 15 == 0 && i != 0) {
  6. try {
  7. System.out.println("兔子开始休息");
  8. Thread.sleep((int) (Math.random() * 15 + 5) * 1000);
  9. } catch (InterruptedException e) {
  10. e.printStackTrace();
  11. }
  12. } else {
  13. try {
  14. Thread.sleep(1000);
  15. System.out.println(Thread.currentThread().getName() + "跑了" + i + "米");
  16. } catch (InterruptedException e) {
  17. e.printStackTrace();
  18. }
  19. }
  20. }
  21. System.out.println("兔子跑完50米,赢了!");
  22. } else {
  23. for (int j = 0; j <= 50; j++) {
  24. try {
  25. Thread.sleep(1000);
  26. System.out.println(Thread.currentThread().getName() + "跑了" + j + "米");
  27. } catch (InterruptedException e) {
  28. e.printStackTrace();
  29. }
  30. }
  31. System.out.println("乌龟跑完50米,赢了!");
  32. }
  33. System.exit(0);
  34. }
  35. }

Main函数

  1. public class Test {
  2. public static void main(String[] args) {
  3. print();
  4. run();
  5. }
  6. public static void print() {
  7. Runnable task = new Print();
  8. Thread t1 = new Thread(task, "B");
  9. t1.start();
  10. try {
  11. t1.join();
  12. } catch (InterruptedException e) {
  13. e.printStackTrace();
  14. }
  15. Thread t2 = new Thread(task, "A");
  16. t2.start();
  17. Thread t3 = new Thread(task, "C");
  18. t3.start();
  19. try {
  20. t2.join();
  21. t3.join();
  22. } catch (InterruptedException e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. public static void run() {
  27. Runnable task = new Racer();
  28. Thread t1 = new Thread(task, "兔子");
  29. Thread t2 = new Thread(task, "乌龟");
  30. t1.start();
  31. t2.start();
  32. }
  33. }