用Runnable接口实现多线程
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; } }
重点:
Thread.sleep(int i);//暂停线程i秒 Thread.currentThread().getName()//获得当前线程名字
原文地址:https://www.cnblogs.com/majestyking/p/12427391.html
时间: 2024-10-06 00:07:57