user6845744
user6845744

Reputation:

multithread initialization synchronisation

Might I ask here for a piece of advice.

I am creating several threads in the constructor of my class as I had a performance issue as I would like to add on more of series and flows. However those threads takes random time to initialize which means the code still execute and putting aside the order of my array list is now messed up, it is not fully loaded when the code keeps executing.

Series is a wrapper which add listeners and to simplify output a series of ArrayList that my frame needs to instantiate a chart in a panel.

what is the correct way to proceed here. I feel I do it all wrong.

    new Thread(new Runnable() {
        public void run() {
            Flow flow = new Flow(idThread, 1);
            flows.add(flow);
            series.add(new Series(3000, ProcessingType.NONE, flow, controller));
            series.add(new Series(5000, ProcessingType.FILTER, flow, controller));
        }
    }).start();

    new Thread(new Runnable() {
        public void run() {
            Flow flow = new Flow(idThread, 2);
            flows.add(flow);
            series.add(new Series(4000, ProcessingType.NONE, flow, controller));
            series.add(new Series(5000, ProcessingType.FILTER, flow, controller));
        }
    }).start();

    Global.getInstance().mySeries(idThread, series);
    trading = new Trading(idThread);

I try naively a

while (series.size()<10){
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

However "logically" the main thread should sleep and allow time for the other ones to initialize?

Thanks

Upvotes: 0

Views: 57

Answers (2)

Shanker Naik
Shanker Naik

Reputation: 57

You can use a CyclicBarrier, where you can call await() method in main, until all you thread have reached this barrier your main thread will wait.

http://tutorials.jenkov.com/java-util-concurrent/cyclicbarrier.html

Upvotes: 0

Lew Bloch
Lew Bloch

Reputation: 3433

Don't extend Thread, implement Runnable. Don't start new threads from within a constructor unless you really like weird bugs. You can use various synchronization idioms such as https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html to "line the horses up at the gate before the race".

Upvotes: 1

Related Questions