Java – calling the run method directly is not a good practice

In most cases, I want to run a piece of code in a new thread, which will take some time, but in some cases, I want to run it with the thread calling the method Is it bad practice to call the run method directly?

If it's not a good idea, is it better to put the code in another method that can be called or copied by a new thread?

Here are some sample code just to illustrate what I want to achieve:

class Main {
    public Main() {
        new Thread(new WorkerThread(1,2)).start(); // This is what I'd do if I wanted it to run in a new thread.
        new WorkerThread(1,2).run(); // Is it bad practice to do this?
    }
}

class WorkerThread implements Runnable {
    private int int1,int2;

    public WorkerThread(int int1,int int2) {
        this.int1 = int1;
        this.int2 = int2;
    }

    public void run() {
        // Do something time consuming with the ints.
    }
}

Solution

I know there are many other answers, but your question is about "practice", and the word doesn't appear in any of them

It is good practice to write code that is easy for others to understand, and it is best to understand it without any inline comments

Call foobar Run () has no problem, as long as the meaning of "run" is obvious to the reader of the program

Your class name is workerthread, even if it is not a thread This can be confusing And call workerthread Run () may be more confusing as to whether they involve a thread

I'll say, if it makes sense, continue calling the run () method, but change the class so that the reader knows you're not trying to start a thread and execute it in the wrong way

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>