zoukankan      html  css  js  c++  java
  • 一个简单多线程的面试题

    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("执行结果: 
    ");
            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("
    ");
        }
    }
    

      

  • 相关阅读:
    Base64简介
    grafana+graphit安装笔记
    朋友圈里的格局
    设计模式值六大原则——接口隔离原则 (ISP)
    设计模式值六大原则——迪米特法则(LoD)也称为最少知识原则(LKP)。
    设计模式值六大原则——开闭原则(OCP)
    设计模式值六大原则——里氏替换原则(LSP)
    工厂模式
    JSON简介以及用法代码汇总
    sql where 1=1和 0=1 的作用
  • 原文地址:https://www.cnblogs.com/yspworld/p/13058096.html
Copyright © 2011-2022 走看看