SoFunction
Updated on 2025-04-24

Several ways to implement parent-child thread sharing data

There are several main ways to share data between parent and child threads:

1. Shared variables

Parent and child threads can exchange data through shared variables. These variables need to be defined in the parent thread and passed to the child thread to ensure that the child thread can access these variables. It should be noted that shared variables may need to be synchronized in a multi-threaded environment to avoid data competition and inconsistency.

public class SharedVariableExample {
    private static int sharedData = 0;

    public static void main(String[] args) {
        Thread parentThread = new Thread(() -> {
            // Modify shared data            sharedData = 10;
            ("Parent Thread set sharedData to " + sharedData);

            Thread childThread = new Thread(() -> {
                // Access shared data                ("Child Thread sees sharedData as " + sharedData);
            });

            ();
        });

        ();
    }
}

2. Use ThreadLocal

ThreadLocalAllows each thread to have its own independent copy of local variables. AlthoughThreadLocalIt is not directly used for data sharing of parent and child threads, but it can ensure that each thread has its own copy of the data without being disturbed by other threads. In order to realize data sharing between parent and child threads, data can be set in the parent thread and the data can be obtained in the child thread.

public class ThreadLocalExample {
    private static ThreadLocal<Integer> threadLocalData = (() -> 0);

    public static void main(String[] args) {
        (10);

        Thread childThread = new Thread(() -> {
            Integer data = ();
            ("Child Thread sees threadLocalData as " + data);
        });

        ();
    }
}

3. Use the synchronization mechanism

When multiple threads need to access shared data safely, synchronization mechanisms can be used, such assynchronizedKeywords or explicit locks (e.g.ReentrantLock). This ensures that at any time only one thread can access the shared data, thus avoiding data race and inconsistency issues.

public class SynchronizedExample {
    private static int sharedData = 0;

    public static void main(String[] args) {
        Object lock = new Object();

        Thread parentThread = new Thread(() -> {
            synchronized (lock) {
                sharedData = 10;
                ("Parent Thread set sharedData to " + sharedData);

                Thread childThread = new Thread(() -> {
                    synchronized (lock) {
                        ("Child Thread sees sharedData as " + sharedData);
                    }
                });

                ();
            }
        });

        ();
    }
}

4. Use thread-safe data structures

Java provides some thread-safe data structures, such asConcurrentHashMapCopyOnWriteArrayListwait. These data structures can be used to share data between multiple threads and automatically handle synchronization issues.

import ;

public class ConcurrentHashMapExample {
    private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    public static void main(String[] args) {
        ("sharedKey", 10);

        Thread parentThread = new Thread(() -> {
            ("Parent Thread set map value to " + ("sharedKey"));

            Thread childThread = new Thread(() -> {
                ("Child Thread sees map value as " + ("sharedKey"));
            });

            ();
        });

        ();
    }
}

5. Use ExecutorService

If the parent thread and child thread are passedExecutorServiceTo manage it, you canCallableandFutureObjects to pass data.CallableThe result can be returned, and the parent thread can passFutureGet the calculation result of the child thread.

import ;
import ;
import ;
import ;
import ;

public class ExecutorServiceExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = (2);

        Future&lt;Integer&gt; future = (() -&gt; {
            return 10; // Child thread returns data        });

        Integer result = (); // Get the data returned by the child thread        ("Main Thread received result: " + result);

        ();
    }
}

Summarize

Sharing data between parent and child threads can be achieved in many ways, including directly sharing variables and usingThreadLocal, synchronization mechanism, thread-safe data structure andExecutorService. The choice of the right method depends on the specific application scenario and requirements. In a multithreaded environment, ensuring data consistency and avoiding race conditions is very important.

This is the end of this article about several methods for Java to implement data sharing by parent-child threads. For more related Java parent-child threads, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!