一个简单多线程的面试题

pdd的一个面试编程题

题目描述

现有两只队伍A和B,每个队伍各有五个人,初始时每个人的血量都是5。

每隔一秒钟,两支队伍便互相攻击,每个队伍的每个人都会随机挑选对方的一个的人进行攻击,攻击成功的可能性是80%,20%的可能性失败因为对方进行了闪躲。问5秒钟之后,两支队伍各自剩下哪些人存活。

代码实现

用了两个java class,第一个是mythread,实现了Runnable接口,override run()方法。第二个class里面定义main方法运行。java数组是引用数据类型,每次执行都是上一轮攻击修改之后的数据。

mythread类:

package com;
public class mythread implements Runnable {
    private String name; // 表示线程的名字
    public int attackAimBlood[] = {5, 5, 5, 5, 5};
    // 构造方法
    public mythread(String name) {
        this.name = name;
    }
    public mythread(String name, int[] blood) {
        this.name = name;
        this.attackAimBlood = blood;
    }
    @Override
    public void run() {
        for(int i=0; i<5; i++) {
            // double random=Math.random();//返回[0,1)随机数
            int aim = (int)(Math.random() * 5); //返回0-4;随机数
            // 寻找攻击目标
            while(attackAimBlood[aim]==0) {
                aim = (int)(Math.random() * 5);
            }
            // success表示对方是否闪避成功
            boolean success = ((int)(Math.random() * 5))==0 ? true: false;
            if(!success) {
                attackAimBlood[aim]--;
            }
        }
    }
}

Runnabledemo类:

package com;

public class Runnabledemo {

    public static void main(String[] args) {
        int a[] = {5, 5, 5, 5, 5};
        int b[] = {5, 5, 5, 5, 5};
        int time = 5;
        while(time > 0) {
            time--;
            mythread mt1 = new mythread("线程a", a);
            mythread mt2 = new mythread("线程b", b);
            Thread t1 = new Thread(mt1);
            Thread t2 = new Thread(mt2);
            t1.start();
            t2.start();
        }
        System.out.println("执行结果: \n");
        for(int i=0; i<5; i++) {
            System.out.print(a[i] + "  ");
        }
        System.out.println();
        for(int i=0; i<5; i++) {
            System.out.print(b[i] + "  ");
        }
        System.out.println("\n");
    }
}

  

posted @ 2020-06-07 00:07  我喜欢旅行  阅读(165)  评论(0编辑  收藏  举报