fanjavaid
fanjavaid

Reputation: 1738

Running two tasks simultaneously in Java

I have two tasks that should be run together. The first task to save the data to the database. And the second task of recording video.

Currently I use a Thread for each task, and run it simultaneously.

...
Thread insertDb = new Thread(new Runnable() {
            @Override
            public void run() {
                // Insert to Database
                setDataMediaVisit(thumbStr);
                insertVisitRecord();
            }
        });

        Thread capture = new Thread(new Runnable() {
            @Override
            public void run() {
                if (getGraph().getState() == DSCapture.PREVIEW) {
                    getGraph().setCaptureFile("data/"+ CaptureController.getNoMr() +"/videos/"+videoStr, DSFilterInfo.filterInfoForProfile(new File("profiles/demo_profile800x570_WM8_VBR_100.prx")), DSFilterInfo.doNotRender(), true);
                    getGraph().record();
                }

                setData(CaptureController.getNoMr());
            }
        });

        insertDb.start();
        capture.start();
...

Is the above code thread safe? I want to use EDT, but i know EDT for Java Swing Component. CMIIW

Thank you.

Upvotes: 2

Views: 1078

Answers (1)

user1079877
user1079877

Reputation: 9358

THread safe is just an issue, when do you want use object that are running in specific thread with another thread. It's not clear here that you are using the share object in this 2 thread or not! But, if you wanna use some share object or you want to read and write from file or specific butter, you can use lock object like this:

final Object lock = new Object();

// In thread 1
// TODO: do some process in thread on

synchronized(lock) {
    // TODO: Put the result in somewhere that thread2 want to read it
}


// In thread 2
synchronized(lock) {
    // TODO: get the result from the place that you put in thread 1
}

// TODO: do some process on thread 2 on the data

You should always remember that you need to put smallest possible synchronized, because if the other thread reach to synchronized part, it will wait until thread 1 finish synchronized block and it can kill the performance of your code

Upvotes: 1

Related Questions