javaAPI 多线程 模拟接力赛跑

public class RunThread implements Runnable {
    int M = 100000;
    int anInt;
    boolean is   =true;
    @Override
    public void run() {
        while (is){
            synchronized (this){
                if (M<=0) {
                    System.out.println("跑完啦");
                    is = false;
                    return;
                }
                if (anInt==100){
                    anInt = 0;
                }
                if (anInt == 0){
                    System.out.println(Thread.currentThread().getName()+"选手拿到了接力棒!");
                }
                anInt = anInt+10;
                M = M-10;
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+"选手跑了"+anInt+"米"+"总路程还剩"+M+"米");
            }
        }
    }
}
class Test6{
    public static void main(String[] args) {
        RunThread runThread = new RunThread();
        Thread thread1 = new Thread(runThread,"一号");
        Thread thread2 = new Thread(runThread,"二号");
        Thread thread3 = new Thread(runThread,"三号");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}

你可能感兴趣的:(开发语言,java,后端,架构)