Java多线程--实现跑马小游戏

线程的实现方式

  1. 继承Thread类:void run()方法没有返回值,无法抛异常
  2. 实现Runnable接口:void run()方法没有返回值,无法抛异常
  3. 实现Callable接口:V call() throws Exception 返回结果,能够抛异常

实现Callable接口

(1)创建Callable接口的实现类,并实现call()方法,该call()方法将作为线程执行体,并且有返回值。

(2)创建Callable实现类的实例,使用FutureTask类来包装Callable对象,该FutureTask对象封装了该Callable对象的call()方法的返回值。

(3)使用FutureTask对象作为Thread对象的target创建并启动新线程。

(4)调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

任务

四匹马,跑一千米比赛,每匹马的速度通过1~10的随机数来产生,输出哪匹马是冠军

RunTask1.java代码:

复制代码
import java.util.Random;
import java.util.concurrent.Callable;

/**
 * 跑步任务
 */

public class RunTask1 implements Callable<Long> {
    // step/100ms 是否睡着 睡觉时间
    // 通过方法形参接收参数
    // 定义属性
    private int step;
    private boolean isSleep;
    private int sleepTime;
    public RunTask1(int step,boolean isSleep,int sleepTime){
        this.step=step;
        this.isSleep=isSleep;
        this.sleepTime=sleepTime;
    }
    @Override
    public Long call() throws Exception {
        int distance=0;
        long start = System.currentTimeMillis();
            while(true){
                distance+=step;
                if (isSleep) {
                    if (distance == 800) { //跑到800米
                        try {
                        System.out.println(Thread.currentThread().getName() + "睡" + sleepTime + "ms");
                        Thread.sleep(sleepTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(distance>=1000){
                break;
            }
            System.out.println(Thread.currentThread().getName() + "跑完" + distance + "米");
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return System.currentTimeMillis()-start;
    }
}

Test.java代码

复制代码
import java.util.Random;
import java.util.concurrent.FutureTask;


public class Test {
    public static void main(String[] args) throws Exception {
        //第一匹马的跑步任务
        RunTask1 horse1=new RunTask1(new Random().nextInt(10)+1,true,200);
        FutureTask<Long> horseResult = new FutureTask<>(horse1);
        Thread t1=new Thread(horseResult,"马1");

        //第二匹马的跑步任务
        RunTask1 horse2=new RunTask1(new Random().nextInt(10)+1,true,400);
        FutureTask<Long> horseResult1 = new FutureTask<>(horse2);
        Thread t2=new Thread(horseResult1,"马2");

        //第三匹马的跑步任务
        RunTask1 horse3=new RunTask1(new Random().nextInt(10)+1,true,5500);
        FutureTask<Long> horseResult2 = new FutureTask<>(horse3);
        Thread t3=new Thread(horseResult2,"马3");

        //第四匹马的跑步任务
        RunTask1 horse4=new RunTask1(new Random().nextInt(10)+1,false,0);
        FutureTask<Long> horseResult3 = new FutureTask<>(horse4);
        Thread t4=new Thread(horseResult3,"马4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();

        //统计比赛结果,一定要等main线程执行,否则, Horse1的线程还没跑完,就输出了winner is Horse2
        if((horseResult.get().longValue() < horseResult1.get().longValue()) && (horseResult.get().longValue() < horseResult2.get().longValue()) && (horseResult.get().longValue() < horseResult3.get().longValue())){
            System.out.println("winner is "+t1.getName());
        }
        else if((horseResult1.get().longValue() < horseResult.get().longValue()) && (horseResult1.get().longValue() < horseResult2.get().longValue()) && (horseResult1.get().longValue() < horseResult3.get().longValue())){
            System.out.println("winner is "+t2.getName());
        }
        else if((horseResult2.get().longValue() < horseResult.get().longValue()) && (horseResult2.get().longValue() < horseResult1.get().longValue()) && (horseResult2.get().longValue() < horseResult3.get().longValue())){
            System.out.println("winner is "+t3.getName());
        }
        else if(horseResult3.get().longValue() < horseResult.get().longValue() && (horseResult3.get().longValue() < horseResult1.get().longValue()) && (horseResult3.get().longValue() < horseResult2.get().longValue())){
            System.out.println("winner is "+t4.getName());
        }
        else System.out.println("平局");
    }
}

控制台输出,想要结果不一样,可以通过设置哪一匹马会睡眠,从而改变结果,代码还是有不足:

相关推荐
q***071411 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
q***498611 小时前
Spring Boot 3.4 正式发布,结构化日志!
java·spring boot·后端
一晌小贪欢14 小时前
【Python数据分析】数据分析与可视化
开发语言·python·数据分析·数据可视化·数据清洗
沐浴露z14 小时前
【微服务】基本概念介绍
java·微服务
Z3r4y14 小时前
【代码审计】RuoYi-4.7.3&4.7.8 定时任务RCE 漏洞分析
java·web安全·ruoyi·代码审计
草莓火锅15 小时前
用c++使输入的数字各个位上数字反转得到一个新数
开发语言·c++·算法
j_xxx404_15 小时前
C++ STL:阅读list源码|list类模拟|优化构造|优化const迭代器|优化迭代器模板|附源码
开发语言·c++
DreamNotOver15 小时前
批量转换论文正文引用为上标
开发语言·论文上标
散峰而望15 小时前
C/C++输入输出初级(一) (算法竞赛)
c语言·开发语言·c++·算法·github