Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel Execution of multiple threads in java

I have to execute multiple instances of my class concurrently. i have written the following code below. I have done it in two ways. But I don't see the difference. What is the right way to have parallel running threads?

Thanks.

Here the snippet:

public class MyClass {

        public MyClass() {
            runnable = true;
        }

        public boolean isRunnable() {
            return runnable;
        }

        public static void main(String[] args) throws InterruptedException {

            /* METHOD 1
             MyClass myclass = new MyClass();

             if (myclass.isRunnable()) {
                 for (int i = 0; i < loop; i++) {
                     myclass.execTask();      
                     Thread.sleep(sleep);
                 }
             }
             */

                  //METHOD 2
            final MyClass myclass = new MyClass();


            ExecutorService threadPool = Executors.newFixedThreadPool(threadNo);

            for (int i = 0; i < threadNo; i++) {
               threadPool.submit(new Runnable() {
                    public void run() {
                        for (int i = 0; i < loop; i++) {
                        myclass.execTask();
                            try {
                                Thread.sleep(sleep);
                            } catch (InterruptedException ex) {
                                Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
                            }
                        }
                    }
                });
            }
            threadPool.shutdown();

            public void execTask(){
            .........
            }
        }
    }
like image 461
user907810 Avatar asked Jul 02 '26 13:07

user907810


1 Answers

The difference between your two methods is that in "Method 2," you may actually have multiple threads of execution (assuming that threadNo is greater than 1). Method 2 allows for multiple work threads to grab a Runnable and call execTask (by calling run) in parallel (concurrently, to be precise). The pause in "Method 2" does pretty much nothing.

"Method 1" executes entirely on the "Main" thread. It calls execTask, waits, and then calls it again. This will call the execution some number of times serially.

(I assume this is pseudo-code because parts of it won't compile.)

Here is a cleaned-up "Method 2". Note that I have threadNo worker threads (it helps if this is larger than 1) and I create loop Runnables.

ExecutorService threadPool = Executors.newFixedThreadPool(threadNo);

for (int i = 0; i < loop; i++) {
    threadPool.submit(new Runnable() {
        public void run() { myclass.execTask(); });
}
like image 88
Charles Forsythe Avatar answered Jul 05 '26 02:07

Charles Forsythe



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!