0

这是我的配置文件(Test.txt)

CommandA   75%
CommandB   15%
CommandC   10%

我写了一个多线程程序,我在其中逐行读取文件,但不知道我应该怎么做上面的问题,其中这么多百分比(75%)的随机调用转到 CommandA,而这么多百分比(15%)的随机调用转到 CommandB,与 CommandC 相同。

public static void main(String[] args) {

            for (int i = 1; i <= threadSize; i++) {
                new Thread(new ThreadTask(i)).start();
            }
        }

class ThreadTask implements Runnable {

        public synchronized void run() {
            BufferedReader br = null;

            try {
                String line;

                br = new BufferedReader(new FileReader("C:\\Test.txt"));

                while ((line = br.readLine()) != null) {
                    String[] s = line.split("\\s+");
                    for (String split : s) {
                    System.out.println(split);
                }
            }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null)br.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }

        }
    }
4

1 回答 1

3

获取一个随机数 1-100。如果编号是 1-75 执行命令 A,76-90 执行命令 B,91-100 执行命令 C。

编辑评论:

有两种方法我会考虑这样做。如果你只有三个命令(A、B、C),那么你可以做一个简单的:

    int[] commandPercentages = {75, 15, 10};        
    int randomNumber = 90;

    if((randomNumber -= commandPercentages[0]) < 0) {
        //Execute Command A
    }
    else if((randomNumber -= commandPercentages[1]) < 0) {
        //Execute Command B
    }
    else {
        //Execute Command C
    }

如果你有很多复杂的命令,你可以像这样设置命令:

private abstract class Command {
    int m_percentage;       
    Command(int percentage) {
        m_percentage = percentage;
    }       
    int getPercentage() {
        return m_percentage;
    }
    abstract void executeCommand();
};

private class CommandA extends Command {        
    CommandA(int percentage) {
        super(percentage);
    }
    @Override
    public void executeCommand() {
        //Execute Command A
    }       
}

private class CommandB extends Command {        
    CommandB(int percentage) {
        super(percentage);
    }
    @Override
    public void executeCommand() {
        //Execute Command B
    }

}

然后像这样选择命令:

    Command[] commands = null;  
    int randomNumber = 90;

    commands[0] = new CommandA(75);
    commands[1] = new CommandB(25);

    for(Command c: commands) {
        randomNumber -= c.getPercentage();
        if(randomNumber < 0) {
            c.executeCommand();
        }
    }
于 2012-05-15T19:43:34.490 回答