Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Threading Basics

What is the difference between the two thread calls below? Will the two calls act similarly?

NOTE: I am not using #1 & #2 at the same time, which is the best option.

private void startConnections(){
    ServerThread server = new ServerThread();
    server.start(); // #1
    Thread serverThread = new Thread(server);
    serverThread.start(); //#2
}

class ServerThread extends Thread{
    public void run(){}
}
like image 918
sravanreddy001 Avatar asked Jan 18 '23 06:01

sravanreddy001


1 Answers

The first approach is acceptable, but discouraged. The second one works, but is broken/hard to understand. Consider the third one:

class ServerRunnable implements Runnable {
  public void run(){}
}

Runnable run = new ServerRunnable();
Thread serverThread = new Thread(run);
serverThread.start();  //#3

#1

This is pretty common approach - in order to create a new thread you are simply subclassing it and calling start() method. Many people, including myself, find this idiom being a poor practice - it unnecessarily couples task (contents of run() method) with threading (Thread class).

#2

I have never seen code like this and although technically working, I would correct it immediately. Even though you are creating a thread instance, you are passing it to another thread and starting the latter. So why creating the first thread on the first place? Note that Thread also implements Runnable, so it technically works, but is really awkward.

#3

So what do I recommend? Implement Runnable interface that is not coupled to threading. You cannot run Runnable in a separate thread alone, you have to explicitly create that thread. But having raw Runnable also allows you to easily switch from native thread to for instance thread-pool.

Technically you can extend Thread and put such a "runnable" in a thread pool, but this is really hard to understand and you are also unnecessarily carrying Thread baggage (it is quite a big class).

like image 143
Tomasz Nurkiewicz Avatar answered Jan 28 '23 17:01

Tomasz Nurkiewicz