簡體   English   中英

如何從另一個線程訪問一個線程的方法?

[英]How can I access the method of one thread from another thread?

我當前開發的應用程序應創建一堆線程,每個線程都包含一些數據收集並自己創建一堆線程。 這些線程(第三層)應該接收一些數據並將其發送到其父線程中的集合,然后,該父線程將進一步發送此數據。

我的問題是我找不到一種方法來訪問集合本身或從另一個線程修改它的方法。 有什么建議么?

您的問題陳述非常模糊,因此我只能指出一些可能會或可能不會幫助您的資源:

如果僅希望在父線程子線程之間共享一個集合,則可以聲明一個變量並將其傳遞給子線程。 那么,如何將其傳遞給子線程? 好吧,您可以創建一個Runnable或其他一些可執行文件來保存您的對象,如下面的示例所示( Runnable可以在另一個線程中執行)。

public class MyRunnable implements Runnable {
    private final Queue<String> sharedQueue;

    public MyRunnable(Queue<String> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }

    public void run() {
        // do stuff with sharedQueue here
    }
}

並啟動一個線程:

final Queue<String> q = new ConcurrentLinkedQueue<>();
new Thread(new MyRunnable(q)).start();

另一種選擇是使用匿名內部類(或lambda),如下面的示例所示,該類僅啟動一堆期貨並將數據共享到Queue (這很可能是共享數據的理想選擇):

// Shared data
final Queue<String> q = new ConcurrentLinkedQueue<>();

// Declare some threads (you can skip this part and instead use the ForkJoinPool)
// which is the default thread pool for CompletableFuture
ExecutorService executorService = Executors.newFixedThreadPool(3);

// Create tasks, complete all of them
CompletableFuture<Void> future = CompletableFuture.allOf(
    CompletableFuture.runAsync(() -> q.offer(Thread.currentThread().getName()), executorService),
    CompletableFuture.runAsync(() -> q.offer(Thread.currentThread().getName()), executorService),
    CompletableFuture.runAsync(() -> q.offer(Thread.currentThread().getName()), executorService),
    CompletableFuture.runAsync(() -> q.offer(Thread.currentThread().getName()), executorService),
    CompletableFuture.runAsync(() -> q.offer(Thread.currentThread().getName()), executorService)
);

// Wait for the threads to complete
future.get();

// Print the result
q.forEach(System.out::println);

如果我理解正確,構造第3層線程時將第2層線程作為參數。 然后,第3層線程可以直接從第二層線程訪問集合,或者可能更好,調用第二層線程的receiveData(...)方法。

您可能需要查看ExecutorServiceCallable 它不會滿足您的要求 ,因為它不會將結果放入集合中,但可能正是您所需要的

這是一個例子。

package whatever;

import java.util.*;
import java.util.concurrent.*;
import java.lang.*;
import java.io.*;

class Example
{
    public static void main (String[] args) throws java.lang.Exception
    {
        ExecutorService executor = Executors.newFixedThreadPool(2);
        Future<String> result = executor.submit(new Callable<String>() {
            public String call() throws Exception {
                Thread.sleep(20);
                return "some data";
            }
        }
        );
        String value = result.get();
        System.out.println("The thread returned:" + value);
    }
}

調用executor.submit啟動一個線程並返回Future 當線程返回時,它將值放入Future ,並且父線程可以在調用就緒時通過調用get來檢索它。 您可以使用其他方法來驗證線程是否已完成。

從您的問題尚不清楚這是否滿足要求,但是由於它實現起來很簡單,因此,如果滿足您的要求,您可能要考慮使用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM