LolPeng478
LolPeng478

Reputation: 11

Java: Start Thread (Alternative to starting in constructor)

Is there an alternative way to start a thread when an object is made (when the constructer is called). I know you can't start the thread in a constructor. But what if I have two methods in the class (class is called Tasks) which implements Runnable: run(), continuousRecv(). The run() method calls the continuousRecv() function. The continuousRecv() does some stuff. Then I create a private class within the public class Tasks called startContRecv() and in the constructor function call start the thread, like so

Thread t1 = new Thread(new Tasks());
t1.start();

My code:

import java.lang.Runnable;

public class Tasks implements Runnable {
    public Tasks() {
        startContinousReceive conRecv = new startContinousReceive();
    }

    public void continuiousReceive() {
        while (true) {
            //Code to executed
        }
    }

    public void run() {
        continuiousReceive();
    }

    //PRIVATE CLASS WHICH STARTS THREAD
    //INSTANCE OF PRIVATE CLASS IS MADE IN CONSTRUCTOR OF TASKS CLASS

    private class startContinousReceive {
        public startContinousReceive() {
            Thread t1 = new Thread(new Tasks());
            t1.start();
        }
    }
}

Upvotes: 1

Views: 1061

Answers (3)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77464

Why?

It is an antipattern to do a lot of work in the constructor.

In particular, it breaks your ability to subclass the constructor.

So don't try to start the thread in the constructor!

Why is code like

new MyThread().start();

bad? It is very readable: make a new Thread and run it.

If you want, you can still wrap this in a method:

public void startNewThread() {
  new MyThread().start();
}

Upvotes: 1

iullianr
iullianr

Reputation: 1284

The easiest way to achieve what you want: when creating a task also start a thread with it is to define a factory method in Tasks class, and make the Tasks constructor private. See below:

public static void createTask( ) {
    Tasks t = new tTasks();
    Thread t  = new Thread( t) ;
    t.start( );
}

And declare your constructor private, in order to make sure that the only way Tasks is instantiated, is through this factory method. Otherwise you will not get also a Thread started. Also, you should drop your inner private class, is useless in this scenario.

Upvotes: 1

iullianr
iullianr

Reputation: 1284

You will get an infinite loop of instantiating Tasks objects which will end-up in an OutOfMemoryError for sure. You instantiate object1 of Tasks which in turns instantiate your private class which again instantiate another object2 of Tasks and the cycle starts over.

Upvotes: 1

Related Questions