Thread only works once

When the thread is completed, you cannot start it again using the start () method: it throws an exception. Can anyone explain why? What is behind such an architectural solution?

+5
source share
5 answers

Since the way to have code executed in a separate thread is not to create a thread that is related to the system representation of what the thread is (there are endless details about the difference between green and system threads), but to create a Runnable and execute it in the thread.

For optimal code (since creating threads takes a lot of time), I would recommend that you do not directly run a Runnable by a thread, but rather an ExecutorService , which allows you to use a thread pool without worrying about all these details.

+7
source

When the thread is completed, you cannot run it again using the start () method:

Bugfix: you can call Thread.start()only once for each instance, any subsequent call throws an exception, regardless of whether this thread works or not.

"" , ( , ) , , ( ), ; , , .

+5

, , . , Thread . , . !

+2

, , , .

Place the loop inside the run () method if you want it to execute the procedure more than once. You can use the callback method to send data / signals back to the calling stream and respond to them when they occur.

0
source

Simple implementation for creating multiple threads:

import java.io.*;

class PWD extends Thread {
   public void run() {
   System.out.println(System.getProperty("user.dir"));
   return;
   }
}
public class HelloMultithread extends Thread{
   public static void main(String[] args) throws java.io.IOException {
      for(int i = 0; i < 10; i++){
      PWD p = new PWD();
      p.start();
      }
   } 
}

As a newbie, this link helped:

http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html

0
source

All Articles