Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way of implementing multithreading in java?

I have been following several YouTube demos and tutorials on implementing multi-threaded operations in Java. However, all the tutorials show this following procedure:

class Task implements Runnable {
    @Override
    public void run() {
        doTask();
    }

    public void doTask() {
        for (int i = 0; i < 1500; i++) {
            System.out.print('T');
        }
    }
}

public class Main {

    public static void main(String[] args) {
        Task t = new Task();

        Thread thread = new Thread(t);
        thread.start();

        for (int i = 0; i < 1500; i++) {
            System.out.print('M');
        }
    }
}

Some demos extends Thread class instead of Runnable, however, they follow a similar concept.

However, one problem that I reckon is that what if I want to have multiple logics in a class that I want to run concurrently, then, I have a issue. Well, Java veterans may know some trick to do so. However, I tried to implement such logic in a different way. Here is the code that I wrote:

class Task {
    public void doTask() {
        for (int i = 0; i < 1500; i++) {
            System.out.print('T');
        }
    }
}

public class Main {

    public static void main(String[] args) {
        Task t = new Task();

        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                t.doTask();
            }
        });
        thread.start();

        for (int i = 0; i < 1500; i++) {
            System.out.print('M');
        }
    }
}

Now, I can launch several threads and call the particular method that I want run concurrently.

Now, I want to know is there any benefit of implementing multi threaded operation using the first approach and is there any shortcomings of the latter one?


1 Answers

There is no point in defining a Runnable class with a run() method that only invokes doTask. Just put the contents of doTask in run.

Or, better, use a lambda:

Thread thread = new Thread(() -> {
  // Stuff you want to do.
});

But there is absolutely no good reason to extend Thread.

In fact, in many cases you don't want to use Thread directly: instead, use an ExecutorService, to which you submit Runnable/Callable instances.

like image 188
Andy Turner Avatar answered Jan 28 '26 11:01

Andy Turner



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!