I'm about learning Threads in Java. I just created a new thread it's fine there, I want program to be closed when some operation is done, but when I call System.exit(0);
inside thread, the program won't close!
code:
public class Humaida
{
public Thread thread;
public Humaida()
{
thread = new Thread(() -> //i guess it using lambda expression,i just copied it
{
try
{
System.out.println("inside thread");
System.exit(0); // i think this line have to close\terminate JVM or the whole program
} catch (Exception e)
{
e.printStackTrace();
}
});
thread.start(); //IMO this should be last line to execute
System.out.println("after thread.start"); //shouldn't be run cause System.exit(0); reached
printIt("after reading thread"); // i used my method just to ensure that program running
}
public static void main(String[] args)
{
new Humaida();
}
public void printIt(String text)
{
System.out.println(text);
}
}
I get some strange output like
1st run:
after thread.start
inside thread
Press any key to continue . . .
2nd run:
after thread.start
after reading thread
inside thread
Press any key to continue . . .
3rd run:
after thread.start
inside thread
after reading thread
Press any key to continue . . .
Let's forget the different output for same code, that isanother problem.
I searched for some solution, I tried System.exit(-1);
and thread.kill()
but it doesn't work either.
What is happening here?
Does System.exit(0);
just kill this thread, and not the main thread?