When will this thread stop running and stop existing? Will it stop running immediately after printing the number 10
? Is it available for garbage collection immediately after printing 10
? Or must I explicitly interrupt it or something?
Runnable counter = new Runnable() {
@Override
public void run() {
for (int i =0; i<=10; i++) {
System.out.println(i);
}
}
};
new Thread(counter).start();
A thread doesn't commit suicide. It simply terminates or gets aborted (say, killed).
There is an important factor that justifies the usage of a so brutal term, killing, for process and threads: their state is not saved and transactional integrity is not directly guaranteed unless you have another mechanism.
In your case, the thread will simply print from 1 to 10 and terminate, being garbaged the next time GC runs.
Nothing more.