简体   繁体   中英

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

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?

You should not. Override run instead

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 .

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 onlate binding and the proper method will be invoked automatically:

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

You can override start as any other method

    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 start does some magic (native code) that you hardly can mimic.

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.

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.

    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...

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

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

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 ).

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 ).

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

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.

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.

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 .

class Worker implements Runnable{

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

private void runFoo(){ // something }

private void runBar(){ // else }

}

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

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

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

It is discouraged to override Thread, if possible create an implementation of the Runnable interface instead and run that on a thread. This can also be done with a lambda expression, making everythin super short and simple.

// create a new thread and give it a Runnable with a lambda expression and a custom name
Thread thread = new Thread(() -> {
    // put your code here
}, "CustomThreadName");

// start it
thread.start();

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.

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 thread and is specialised.

We can override start/run method of Thread class because it is not final. But it is not recommended to override start() method

class Bishal extends Thread { 
public void start() 
    { 
        System.out.println("Start Method"); 
    } 
public void run() 
    { 
        System.out.println("Run Method"); 
    } 
} class Main{ 
public static void main(String[] args) 
    { 
        Bishal thread = new Bishal(); 
        thread.start(); 
        System.out.println("Main Method"); 
    } 
} 

when we are calling start() method by an object of Bishal class, then any thread won't be created and all the functions are done by main thread only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM