Home >Java >javaTutorial >How to Share Data Between Two SwingWorker Classes in Java?
How to Share Data Between Two SwingWorker Classes in Java
Introduction
When working with multiple threads in a Java application, it sometimes becomes necessary to share data between them. The SwingWorker class, which extends SwingUtilities, provides a convenient way to perform time-consuming tasks in a separate thread, without blocking the main event dispatch thread.
Problem Statement
Consider a scenario where you have two SwingWorker classes, FileLineCounterThread and FileDivisionThread, each responsible for performing different tasks. Suppose you want to pass the result from the FileLineCounterThread to the FileDivisionThread.
Solution
Sharing data between SwingWorker classes involves two steps:
Communicating from the background thread to the EDT thread:
Listening for property changes in the EDT thread:
Sample Implementation
The following code snippet demonstrates how to implement the above steps:
import javax.swing.SwingWorker; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; public class DataSharingSwingWorker { public static void main(String[] args) { // Create the SwingWorker instances SwingWorker<Integer, Void> lineCounterWorker = new LineCounterWorker(); SwingWorker<String, Void> divisionWorker = new DivisionWorker(); // Add a listener to the line counter worker lineCounterWorker.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if ("result".equals(evt.getPropertyName())) { // Retrieve the line count from the event int lineCount = (int) evt.getNewValue(); // Pass the line count to the division worker divisionWorker.passData(lineCount); } } }); // Execute the workers lineCounterWorker.execute(); divisionWorker.execute(); } private static class LineCounterWorker extends SwingWorker<Integer, Void> { @Override protected Integer doInBackground() throws Exception { // Perform line counting return null; // Placeholder for line count } @Override protected void done() { firePropertyChange("result", null, get()); } } private static class DivisionWorker extends SwingWorker<String, Void> { private int lineCount; public void passData(int lineCount) { this.lineCount = lineCount; } @Override protected String doInBackground() throws Exception { // Perform division operation based on the line count return null; // Placeholder for division result } @Override protected void done() { System.out.println("Division result: " + get()); } } }
Conclusion
By leveraging the PropertyChangeListener mechanism, SwingWorker classes can effectively share data between parallel threads, allowing greater flexibility and control in complex multithreaded applications.
The above is the detailed content of How to Share Data Between Two SwingWorker Classes in Java?. For more information, please follow other related articles on the PHP Chinese website!