Runnable interface to achieve multi-threaded use
public class ThreadDemo { public static void main(String[] args) throws InterruptedException { Racer racer = new Racer(); new Thread(racer, "乌龟").start(); new Thread(racer, "兔子").start(); } } class Racer implements Runnable { private String winner; //重写run()方法 @Override public void run() { for (int step = 0; step <= 100; step++) { //模拟让兔子睡觉 if(Thread.currentThread().getName().equals("兔子") && step%10==0 ){ try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(Thread.currentThread().getName() + "跑了第" + step + "步."); boolean flag = isGameOver(step); if (flag) { break; } } } public boolean isGameOver(int steps) { if (winner != null) { return true; } else { if (steps == 100) { winner = Thread.currentThread().getName(); System.out.println("胜利者是:" + winner); return true; } } return false; } }
Key:
Thread.sleep ( int i); // Pause thread i seconds Thread.currentThread () getName (). // get the name of the current thread