Can a Java thread live more than once?

Good ... Let me try to explain it as best as possible. Also: this is for mods in minecraft. So, I created a stream object

public static Thread KillThread = new Thread(); 

Then in the constructor of my main class, which is called when the game (Mine craft starts), I

 KillThread = new Thread(new KillAuraThread()); 

KillAuraThread is the name of the class that is the thread. So I created the stream now. Is this something that annoys me? The stream will work exactly 1 second and it cannot work several times, otherwise it will destroy the delay point and the stream.

 if(KillAura.enabled && !KillThread.isAlive()) { System.out.println("Go AURA!"); try { KillThread.start(); }catch (Exception e) { e.printStackTrace(); } } 

This is called every tick in the game, where it sends location updates, etc.

Now this is where I have the problem. As soon as the flow begins, it becomes “alive”, and when it ends, it is no longer “alive”. But can threads start only once? because after the first run it no longer works? And ideas? Links?

+4
source share
2 answers

Yes, Threads can only be run once, you cannot reuse the Thread object.

Cannot start a thread more than once. In particular, the thread cannot be restarted after completion of execution. See java.lang.Thread.start()

Regardless of this fact, do not use Thread.State to control the life cycle of a thread.

+7
source

You are right, threads can only be started once, and it is illegal to start / start a stream more than once . You should use a while to save the stream.

Instead of using Threads directly, you should use the classes inside the java.util.concurrent package to schedule a fixed task regularly, which is what you are trying to do. Take a look at ThreadPoolExecutor .

+5
source

Source: https://habr.com/ru/post/1432835/


All Articles