Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create 2 threads and communicate between them

I want to make a background task in one thread and send information from that thread to another thread which runs the main program and update the information each period of time.

Thread1:

public void doTask()
{
    // ...
    someData = ...;
}

Thread2:

SwingUtilities.invokeLater(new Runnable()
{
    public void run()
    {
        new MainFrame(someData);
    }
});

How could I achieve this in java?

like image 482
Eng.Fouad Avatar asked Dec 03 '25 16:12

Eng.Fouad


2 Answers

Use the Java Concurrency API. Usage of BlockingQueues, Future<> will help you.

Note: This is a classic producer-consumer problem. This can be achieved having a shared queue to hold data where one thread will push data into the queue and the othe will consume the data. Proper synchronisation is needed to achieve a correct solution. BlockingQueue implementations like LinkedBlockingQueue will be helpful.

Update: Part of you problem [the consumer] can be derived from this answer of mine. But this solution uses the simpler wait-notify approach.

like image 128
Swaranga Sarma Avatar answered Dec 05 '25 04:12

Swaranga Sarma


I using Executor/ExecutorService, output from these methods starting java.swing.Action (create a new EDT if doesn't exists),

or you can test that For EDT

if (SwingUtilities.isEventDispatchThread()) {...

both ways for your Wratever sould be always in EDT, I vote for wraps output to the GUI into Action

like image 25
mKorbel Avatar answered Dec 05 '25 06:12

mKorbel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!