这是我的配置文件(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();
}
}
}
}
答案 0 :(得分: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();
}
}