我有一个类循环符,它返回一个Integer数组,如下所示:
public class Looper implements Runnable{
public AtomicBoolean keepRunning;
public Looper() {
keepRunning = new AtomicBoolean(true);
}
public void stop() {
keepRunning.set(false);
}
@Override
public void run() {
try {
.
.
.
while (keepRunning.get()) {
int[] A = ..... ;
}
}
}
int[] A
在每次while循环迭代后都有不同的值。现在假设在同一个类中有另一个方法saveReturnValue
,它将在每次while循环执行后存储整数数组并对其执行一些操作。但是由于Runnable
的void
性质,我无法用其他方法得到A的值。是否有任何方法访问int[] A
之外的这个方法?
正如在评论中指出的那样,您可以谷歌"Java生产者消费者队列示例",然后根据您的需要修复该代码。
一般的想法是使用一个线程读,另一个线程写的数据结构,如下所示:
public class Producer implements Runnable{
private LinkedBlockingQueue<int[]> queue;
public Producer(LinkedBlockingQueue<int[]> queue) { this.queue = queue;}
@Override
public void run() {
while (keepRunning.get()) {
int[] a = ..... ;
queue.add(a);
}
}
public class Consumer implements Runnable{
private LinkedBlockingQueue<int[]> queue;
public Consumer(LinkedBlockingQueue<int[]> queue) { this.queue = queue;}
@Override
public void run() {
while (keepRunning.get()) {
int[] a = queue.take(a);
saveValue(a);
}
}
public class MainOrWhatever {
public void whateverMethod {
LinkedBlockingQueue<int[]> theQueue = new LinkedBlockingQueue<int[]>();
Consumer consumer = new Consumer(queue);
Producer producer = new Producer(queue);
executorService.submit(consumer);
executorService.submit(producer);
...
}
}