Java Threading Basics

What is the difference between two streaming calls below? Will two calls act the same?

NOTE. I do not use both # 1 and # 2, 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(){} } 
+4
source share
1 answer

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

 class ServerRunnable implements Runnable { public void run(){} } Runnable run = new ServerRunnable(); Thread serverThread = new Thread(run); serverThread.start(); //#3 

# 1

This is a fairly common approach - to create a new thread, you simply subclass it and call the start() method. Many people, including myself, consider this idiom a bad practice - it does not necessarily connect the task (the contents of the run() method) with threading ( Thread class).

# 2

I have never seen such code, and although it worked technically, I would fix it immediately. Even though you are creating an instance of a thread, you pass it to another thread and start it. So why create the first thread in the first place? Note that Thread also implements Runnable , so it technically works, but is really inconvenient.

# 3

So what do I recommend? Implement a Runnable interface that is not thread related. You cannot run Runnable only in a separate thread, you must explicitly create this thread. But having raw Runnable also allows you to easily switch from your own thread to, for example, a thread pool.

Technically, you can extend Thread and put such a โ€œrunnableโ€ in the thread pool, but it is really difficult to understand, and you also need to carry the Thread baggage (this is a fairly large class).

+9
source

Source: https://habr.com/ru/post/1400758/


All Articles