Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/381.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 返回值的可运行替代方法_Java_Android_Multithreading_Bluetooth - Fatal编程技术网

Java 返回值的可运行替代方法

Java 返回值的可运行替代方法,java,android,multithreading,bluetooth,Java,Android,Multithreading,Bluetooth,我需要一些帮助。我必须继续检查通过蓝牙接收的字节[]。为此,我实现了一个Runnable,问题是它不返回字节[] 为此,我尝试实现Callable而不是Runnable,因为这让我可以返回一个值。但是对于Callable,我不能每0,5秒检查一次变量 那么,更新变量并在需要时获取其值的最佳方法是什么 这是我所做的Runnable: private final Handler refresh_handler = new Handler(); @Override protected void on

我需要一些帮助。我必须继续检查通过蓝牙接收的
字节[]
。为此,我实现了一个Runnable,问题是它不返回
字节[]

为此,我尝试实现Callable而不是Runnable,因为这让我可以返回一个值。但是对于Callable,我不能每0,5秒检查一次变量

那么,更新变量并在需要时获取其值的最佳方法是什么

这是我所做的
Runnable

private final Handler refresh_handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);


Runnable refresh_input = new Runnable() {
    @Override
    public void run() {
        bt_read_input = GlobalVar.bt_input;  //Save received value in a local variable
        refresh_handler.postDelayed(refresh_input, 500);
    }
};


refresh_handler.post(refresh_input);  //Call to the function

您可以使用支持生产者-消费者设计模式的
阻塞队列
解决此问题。这将是您的“待办事项”列表,
制作人将在可用时放置数据(字节[]
),而
消费者将在准备处理数据时从队列中检索数据(字节[]

创建一个
Producer
,它可以连续检查通过蓝牙接收的
字节[]

class Producer implements Runnable {
    private final BlockingQueue<byte[]> byteArrayQueue;

    public Producer(BlockingQueue<byte[]> byteArrayQueue) {
        this.byteArrayQueue = byteArrayQueue;
    }

    @Override
    public void run() {
            // Place your data into the queue
        // byteArrayQueue.put(GlobalVar.bt_input);//put received value into the queue


    }
}
现在开始您的
生产者
消费者

BlockingQueue<byte[]> queue = new LinkedBlockingQueue<byte[]>(1);
new Thread(new Producer(queue)).start();
new Thread(new Consumer(queue)).start();
BlockingQueue=newlinkedblockingqueue(1);
新线程(新生产者(队列)).start();
新线程(新使用者(队列)).start();

尽管Debojit Saikia提供了一个非常有用的解决方案,但我面对这个问题的最终方式是:

private final Runnable refresh_input = new Runnable() {

    @Override
    public void run() {
        bt_read_input = GlobalVar.bt_input;
        }
        refresh_handler.postDelayed(refresh_input, 250);
    }
};

当我想得到变量的值时,我只需要调用全局变量
bt\u read\u input

听起来像是一个典型的生产者-消费者问题。你到底想做什么?我需要做的是做一个函数,不断检查变量值,并返回给我这个值谢谢!还有一件事,生产者和消费者方法可以在UI线程类上实现,也可以在新类中退出。您可以将它们定义为UI线程类的内部类,因为它们将在两个单独的线程中执行。
private final Runnable refresh_input = new Runnable() {

    @Override
    public void run() {
        bt_read_input = GlobalVar.bt_input;
        }
        refresh_handler.postDelayed(refresh_input, 250);
    }
};