如何覆盖java中的thread.start()方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4040424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 10:50:32  来源:igfitidea点击:

how to override thread.start() method in java?

javamultithreading

提问by Anand

I need to implement thread.start() method in my java code. Please let me know through an example of overriding of thread.start() method and how it works?

我需要在我的 java 代码中实现 thread.start() 方法。请通过覆盖 thread.start() 方法及其工作原理的示例让我知道?

回答by Schildmeijer

You should not. Override runinstead

你不应该。覆盖运行,而不是

回答by Manny

You don't override the start, you override the "run". You can simply implement a thread by:

您不会覆盖开始,而是覆盖“运行”。您可以通过以下方式简单地实现一个线程:

new Thread() {
  public void run() {
    //your code here
  }
}.start();
//start will call the logic in your run method

回答by Namalak

Actually, you can call run() to run a thread instead of start() to run a thread. But there is a little difference.

实际上,您可以调用 run() 来运行线程,而不是调用 start() 来运行线程。但有一点不同。

Suppose you create two threads:

假设你创建了两个线程:

Thread t1 = new Thread();
Thread t2 = new Thread();

Case 1 :If you call "t1.run()" and "t2.run()" one after another they will start to run t1 and t2 synchronously (sequentially).

情况 1:如果您一个接一个地调用“t1.run()”和“t2.run()”,它们将开始同步(顺序)运行 t1 和 t2 。

Case 2: If you call "t1.start()" and "t2.start()" one after another they will call their run() methods and start to run t1 and t2 asynchronously (in parallel).

情况 2:如果您一个接一个地调用“t1.start()”和“t2.start()”,它们将调用它们的 run() 方法并开始异步(并行)运行 t1 和 t2 。

回答by Toby

Agree with Schildmeijer, don't override start, override run() instead.

同意 Schildmeijer,不要覆盖 start,而是覆盖 run()。

In fact, although start can be overridden (it's not final), it calls the native start0 method which in turn will cause the VM to call the run method (actually from the context of a native thread/process). The native start0 method has private access, so even if you overrode the start, I can't see how you could reproduce the affect.

事实上,虽然 start 可以被覆盖(它不是最终的),但它调用本地 start0 方法,这反过来会导致 VM 调用 run 方法(实际上是从本地线程/进程的上下文)。本机 start0 方法具有私有访问权限,因此即使您覆盖了 start,我也看不到您如何重现影响。

The client calling start() is within a thread (lets say, the main thread), it's not until the run method has done its thing that another thread will be spawned.

调用 start() 的客户端在一个线程内(比方说,主线程),直到 run 方法完成它的事情才会产生另一个线程。

Take a look at the Sun (ahem, Oracle) tutorial on threads at http://download.oracle.com/javase/tutorial/essential/concurrency/index.html, in particular the section on starting threads.

http://download.oracle.com/javase/tutorial/essential/concurrency/index.html上查看有关线程的 Sun(嗯,Oracle)教程,特别是有关启动线程的部分。

回答by Henning

As others said, overriding Thread.start()is not the way to do it. Usually, I wouldn't override Thread.run()either, but use a Runnable.

正如其他人所说,覆盖Thread.start()不是这样做的方法。通常,我也不会覆盖Thread.run(),而是使用Runnable.

If you have to decide which method to run after the thread has been spawned, you could do something like this:

如果您必须决定在线程产生后运行哪个方法,您可以执行以下操作:

final Runnable runnableA = ...;
final Runnable runnableB = ...;

Runnable r = new Runnable() {
    @Override
    public void run() {
        if (...) {
            runnableA.run();
        } else {
            runnableB.run();
        }
    }
}

Thread thread = new Thread(r);
thread.start();

If, as you say, you have a superclass and a subclass where the run()method is overidden, you can just rely on late bindingand the proper method will be invoked automatically:

如果,如你所说,你有一个超类和一个run()方法被覆盖的子类,你可以只依赖后期绑定,正确的方法将被自动调用:

Runnable couldBeAOrB = ...;
Thread thread = new Thread(couldBeAOrB);
thread.start();

回答by Christian Kuetbach

class Worker implements Runnable{

public void run(){ if("foo"){ runFoo(); } else { runBar(); } }

private void runFoo(){ // something }

private void runBar(){ // else }

}

类 Worker 实现了 Runnable{

public void run(){ if("foo"){ runFoo(); } else { runBar(); } }

private void runFoo(){ // 一些东西 }

private void runBar(){ // else }

}

I'm pretty sure, you needn't to overwrite the start-Method.

我很确定,您不需要覆盖 start-Method。

By the way: Take al look at java.util.concurrent.Callable

顺便说一句:看看java.util.concurrent.Callable

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/Callable.html

回答by user85421

You can override startas any other method

您可以start像任何其他方法一样覆盖

    Thread myThread = new Thread() {

        @Override
        public void start() {
            // do something in the actual (old) thread
            super.start();
        }

        @Override
        public void run() {
            // do something in a new thread if 'called' by super.start()
        }
    };

but you must call super.start()to create a new thread and have run()called in that new thread. The original startdoes some magic(native code) that you hardly can mimic.

但是您必须调用super.start()以创建一个新线程并run()调用了该新线程。原版start做了一些你很难模仿的魔法(本机代码)。

If you call run()directly from within your start()(or any other method), it is executed in the actual thread as a normal method, not in a new thread. There is no reason to use a Thread if you don't want to run some code in a new thread.

如果您run()直接从您的start()(或任何其他方法)内部调用,它将在实际线程中作为普通方法执行,而不是在新线程中执行。如果您不想在新线程中运行某些代码,则没有理由使用线程。

You must put your decision logic in the run()method, maybe using some variable set in the constructor (or another method, eventually in start) if that is really needed. I can not find any reason for needing this variable, it should be enough to test the condition in run()as already suggested elsewhere.

您必须将您的决策逻辑放在run()方法中,start如果确实需要,可以使用构造函数(或其他方法,最终在)中设置的一些变量。我找不到任何需要这个变量的理由,它应该足以测试条件,run()正如其他地方已经建议的那样。

    class MyThread extends Thread {

        private final boolean flag;

        public MyThread(boolean someCondition) {
            flag = someCondition;
        }

    // alternative  
    //    @Override
    //    public synchronized void start() {
    //        flag = <<someCondition>>
    //        super.start();
    //    }

        @Override
        public void run() {
            if (flag) {
                // do something like super.run()
            } else {
                // do something else
            }
        }
    }

but it would be easier to understand and maintain if you do it like @Henning suggested!
It's also a more object oriented solution...

但如果你像@Henning 建议的那样做,会更容易理解和维护!
这也是一个更面向对象的解决方案......

回答by user2450176

If we provide our own implementation of start method then it will work like a normal method call and will work on the current thread stack only. New thread will not be created.

如果我们提供自己的 start 方法实现,那么它会像普通方法调用一样工作,并且只会在当前线程堆栈上工作。不会创建新线程。

回答by VdeX

Yes the start() method can be overridden.
But it should not be overridden as it is implementation in thread class has the code to create a new executable threadand is specialised.

是的,可以覆盖 start() 方法。
但是它不应该被覆盖,因为它在线程类中的实现具有创建新的可执行线程代码并且是专门的。