Run the same Java thread twice [closed]

1

I have a problem and I look for help. I need to execute many times the same thread and I get the error

(java.lang.IllegalThreadStateException)

Does anyone know any way to do it?

    
asked by Javier 09.02.2018 в 18:30
source

1 answer

3

You get IllegalThreadStateException because the run () method is called but the Thread status does not allow it.

What is commonly done is to create a new Thread, for example:

for(int i=0; i<1000; i++){
  new Thread(String.valueOf(i)){
    public void run(){
      System.out.println("Ejecutando Thread: " + getName());
    }
  }.start();
}

If you want to create a class you can create a class that implements Runnable :

public class MyThread implements Runnable{
    int id;
    public MyThread(int i){
        this.id = i;
    }
    public void run(){
        try{
            System.out.println("Run: "+ Thread.currentThread().getName()); 
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

In this way, execute a Thread several times:

 for (int i=0; i<1000; i++){
        System.out.println("Ejecutando Thread:" + i);
        MyThread thread = new MyThread(i);        
 }
    
answered by 09.02.2018 / 19:06
source