【问题标题】:How to randomly choose an instance of a class and execute it's method?如何随机选择一个类的实例并执行它的方法?
【发布时间】:2014-02-03 11:00:07
【问题描述】:

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

消费者线程需要能够随机选择要写入的缓冲区对象的实例 1 或实例 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 }
}

对我来说似乎有些多余。由于主体本身有点大的功能,我可能还需要实现两个以上的缓冲区。有什么想法吗?

【问题讨论】:

    标签: java multithreading function class object


    【解决方案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
    }
    

    【讨论】:

    • 谢谢,不胜感激。我喜欢这里采用的方法和提到的其他方法。你们都给了我一些可以合作的东西。
    【解决方案2】:

    您可以拥有一个额外的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
    }
    

    【讨论】:

    • 再次感谢,不胜感激。我喜欢这里采用的方法和提到的其他方法。你们都给了我一些可以合作的东西。
    【解决方案3】:

    你可以使用一个数组和一个接口(即 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();
    }
    

    【讨论】:

    • 我们的简短规定我们不能使用数组以外的任何 Java 集合类型来解决这个特定的解决方案。不过谢谢!
    • 好的,改为使用数组;)
    • @m0skit0 Runnable 只是零参数方法的一个很好的接口。如果需要传递一些上下文,可以使用自定义接口。
    • 无缘无故地引入Runnable 使一个简单的问题变得过于复杂。只需从数组中选择Buffer
    • 嗯,没错。如果他想要每个缓冲区的自定义行为,那么 Runnables 会有所帮助。
    猜你喜欢
    • 2016-03-18
    • 2019-12-03
    • 2019-11-23
    • 1970-01-01
    • 2013-09-18
    • 2011-12-09
    • 2017-09-29
    • 1970-01-01
    • 2011-10-06
    相关资源
    最近更新 更多