J
J
Jake Taylor2020-06-28 15:35:14
Java
Jake Taylor, 2020-06-28 15:35:14

Is it necessary to declare the Thread class when creating a thread?

Task:
- to create a multi-threaded application.

Implementation method (in sequence):
1) Declare a class that will create a new thread that implements the `Runnable` interface;
2) Next, get an instance of the `Thread` type.

It looks like this:

public class One implements Runnable {
// ...объявляем переменные

    // конструктор
    public One(){
        Thread thread = new Thread(this, "Новое имя потока");

    }
}

Question:
- what is the difference from the method presented below?

public class One implements Runnable {
// ...объявляем переменные

    // конструктор
    public One(){
        Thread.currentThread().setName("Новое имя потока");

    }
}


It is possible not to declare a new `Thread` variable via `new` and use it via the variable name. It turns out that you can use this combination `Thread.currentThread().setName("New thread name")`?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2020-06-28
@n199a

In the first case, a new thread named "New thread name" will be created, executing the run method of an instance of class One. In the second case, the name of the thread that called the One constructor will be changed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question