dimanche 7 mars 2021

Java force create new instance for a Runnable on each thread

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?

Aucun commentaire:

Enregistrer un commentaire