简体   繁体   中英

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

The app I currently developing should create the bunch of threads, each containing some data collection and creating the bunch of threads itself. These threads (third layer) should receive some data and send it to the collection in their parent thread, which then will send this data further.

My problem here is I can't find a way to access either collection itself or the method made to modify it from another thread. Any suggestions?

Your problem statement is very vague, so i can only point to some resources that might or might not help you:

If you simply wish to share a collection between the parent thread and the child threads you can declare a variable and pass it to the child thread. So, how do you pass it to the child thread? Well, you either create a Runnable or some other executable piece that holds your object like in the example below (the Runnable can be executed in another thread).

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
    }
}

And to start a thread:

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

The other alternative is to use anonymous inner classes (or lambdas) like in the example below that simply starts a bunch of futures and shares the data to the Queue (which likely is a good candidate for sharing data):

// 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);

If i understand it right, give the 2nd layer thread as parameter when constructing the 3th layer threads. the 3th layer threads can then access the collections from the second layer threads directly, or probably better, call a receiveData(...) method of the second layer thread.

You may want to look at ExecutorService and Callable . It doesn't do what you ask for because it doesn't put the result in collections but it might just be what you need .

Here's an example.

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);
    }
}

The call executor.submit starts a thread and returns a Future . When the thread returns, it puts the value in the Future and the parent thread can retrieve it, whenever its ready, by calling get . There are other methods you can use to verify that the thread has completed.

It wasn't clear from your question if that would suffice but since it's rather simple to implement, you may want to consider using it if it meets your requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM