Java force create new instance for a Runnable on each thread

Viewed 168

In following runnable class:

public class MyRunnable implements Runnable {
    public void run(){
       System.out.println("MyRunnable running");
    }
  }

To create multiple threads of this, i have multiple options:

1.

for(int i = 0; i < 3; i++ ){
Thread th = new Thread(new MyRunnable());
th.start();
}
  1. MyRunnable mr = new MyRunnable;
       for(int i = 0; i < 3; i++ ){
          Thread th = new Thread(mr);
          th.start();
          }
    

Because i've got some property in MyRunnable that do not want to be shared among multiple threads, how can i force creating a new instance of MyRunnable for everyone that going to use this class, is there a mechanism to force this inside MyRunnable?

2 Answers

Instead of subclassing Runnable, make your MyRunnable extend Thread...
(and maybe rename it MyThread)
...or you could make the Constructor private & create a static factory-method to return a Thread containing MyRunnable. Something like:

public class MyRunnable implements Runnable {

    private MyRunnable() {}

    @Override
    public void run() {
        System.out.println(Thread.currentThread().toString() + " : MyRunnable running");
    }

    public static Thread getThread() {
        return new Thread(new MyRunnable());
    }

    public static Thread getStartedThread() {
        final Thread thread = new Thread(new MyRunnable());
        /**/         thread.start();
        return       thread;
    }

    public static void main(final String[] args) {
        getStartedThread();
        getStartedThread();
        getStartedThread();
    }
}

Executor service

In modern Java, we generally do not address the Thread class directly. Instead, use an executor service to handle the creation of threads.

ExecutorService es = Executors.newCachedThreadPool() ;

for( int i = 0 ; i < 3 ; i ++ )
{
      es.submit( new MyRunnable() ) ;
}

es.shutdown()
es.awaitTermination( 10 , TimeUnit.MINUTES ) ;
Related