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

前端 未结 10 1831
情歌与酒
情歌与酒 2020-12-03 02:07

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?

10条回答
  •  情歌与酒
    2020-12-03 02:40

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

提交回复
热议问题