如何随机选择一个类的实例并执行它的方法?

时间:2014-02-03 11:00:07

标签: java multithreading function class object

我有一个写入两个缓冲区的函数。该类是线程化的,因此有两个缓冲区的多个写入器。换句话说,在多个共享缓冲区上有多个生成器(想象两个输入带)。

消费者线程需要能够随机选择要写入的缓冲区对象的instance1或instance 2,并且我不确定如何以一种似乎并不多余的方式(函数体和缓冲区对象完全相同,只是写入的对象会有所不同。

Pseudocode:

Buffer bufA;
Buffer bufB;

int randRes = random * 2 // Generate 1 or 0.

if randRes = 1 {

    if (bufA.tryInsert) {
    // Do things here
    } else {
    // Do other things here }

} else {

if (bufB.tryInsert) {
    // Do things here
    } else {
    // Do other things here }
}

对我来说似乎有些多余。作为函数,如果正文本身有点大,我可能还需要实现两个以上的缓冲区。有什么想法吗?

3 个答案:

答案 0 :(得分:1)

怎么样?
final Buffer[] twoBuffers = {bufA, bufB};
final int randRes = random * 2; // Generate 1 or 0
final Buffer buffer = twoBuffers[random]; // Now you only have one buffer
if (buffer.tryInsert) {
    // Do things here
} else {
    // Do other things here
}

答案 1 :(得分:0)

您可以拥有一个额外的Buffer对象,该对象将根据randRes值进行设置。

Buffer bufA;
Buffer bufB;
Buffer toBeUsed; // Extra Buffer

int randRes = random % 2 // I think you need the modulo operator

if randRes = 1 {
    toBeUsed = bufA; // Use BufferA
} else {
    toBeUsed = bufB; // else use BufferB
}

if (toBeUsed .tryInsert) { // toBeUsed will be either A or B based on randRes value
    // Do things here
} else {
    // Do other things here
}

答案 2 :(得分:0)

你可以使用数组和接口(即Runnable):

Runnable[] runnables = new Runnable[] {
    new Runnable() { ... },
    new Runnable() { ... },
    new Runnable() { ... }
};
Random random = new Random();

while (someCondition) {
   int randomInt = random.nextInt(runnables.length);
   runnables[randomInt].run();
}