Interesting Thread Behavior in Java

I studied the concept of multithreading in Java, where I met this very interesting behavior. I experimented with various ways to create a stream. The current issue is that we are expanding Thread without implementing the Runnable interface.

On the side of the note, I know that it makes the perfect OO sense for implementing the Runnable interface, and not for extending the Thread class, but for the purposes of this question, suppose we extended the Thread class.

Let t be my instance of my extended Thread class, and I have a block of code that will execute in the background, which is written in my run() method of my Thread class.

It works fine in the background with t.start() , but I'm a little curious and called t.run() . The piece of code executed in the main thread!

What does t.start() that t.run() does not work?

+5
source share
3 answers

This is what the class does. T.start () will actually start a new thread, and then call run () on that thread. If you directly call run (), you run it in the current thread.

 public class Test implements Runnable() { public void run() { System.out.println("test"); } } ... public static void main(String...args) { // this runs in the current thread new Test().run(); // this also runs in the current thread and is functionally the same as the above new Thread(new Test()).run(); // this starts a new thread, then calls run() on your Test instance in that new thread new Thread(new Test()).start(); } 

This is the intended behavior.

+8
source

t.start() just does what it says: it launches a new thread that runs part of the run() code. t.run() - a function call for an object from the current workflow (in your case, the main thread).

Just keep in mind: only when calling the start() function of a thread does a new thread start, otherwise calling its functions (except start() ) is similar to calling a simple function on any other object.

+1
source

t.start() makes its own call to actually execute the run() method on a new thread. t.run() just executes run() on the current thread.

Now,

On the side of the note, I know that it makes an ideal OO sense for implementing the Runnable interface than for extending the Thread class

In fact, this is the perfect OO solution to follow any approach (Runnable implementation or Thread extension). It's not that bad in the sense of OO. The advantage you get when implementing Runnable is that you can make your class an extension of another class (which could actually break your OO design.)

0
source

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


All Articles