There are tons of questions asking basically the same, but using the solutions suggested there brings one problem for me.
Problem: If using a boolean to determine if my thread is allowed to keep running or not, the while loop checking if the stop() method has been called and thus, if the "interrupt"-variable has been set, holds the program flow right there in the while loop. So the actual purpose of my threads, which is running in the background, gets lost.
class MyThread implements Runnable
{
private String name;
private long seconds;
private boolean exitThread = false;
MyThread(String name, long seconds)
{
this.name = name;
this.seconds = seconds;
}
public void run()
{
while (!exitThread)
{
try
{
Thread.sleep(seconds* 1000);
System.out.println("Thread \"" + name+ "\" started...");
return;
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
public void stop()
{
this.exitThread = true;
}
}
The while-loop in method "run()" prevents the program from executing, til the thread has finished/been killed, instead of running in the background as my thread is supposed to be.
Follow-up question: Why would I use the keyword "volatile" on my boolean variable since I want my individual created threads to be able to stop as individual, not to stop all thread if the boolean variable is set "true" once on one running thread?
EDIT: Instantiating of threads:
public void initThreads()
{
MyTimerThread newThread = new MyTimerThread("Thread1, 10);
newThread.run();
threadList.add(newThread);
MyTimerThread newThread = new MyTimerThread("Thread2, 30);
newThread.run();
threadList.add(newThread);
}