Boolean isDaemon() // Check if the thread is a daemon thread.
void setDaemon(boolean on) // thread to daemon thread or user thread
// Change it.
import java.util.*;
class example implements Runnable{
static boolean autoSave = false;
public static void main(String[] args) {
Thread t = new Thread(new example());
t.setDaemon(true);
t.start();
for(int i=1; i<=20; i++)
{
try{
Thread.sleep(1000);
}catch(InterruptedException e){}
System.out.println(i);
if(i==5)
autoSave = true;
}
System.out.println ("Exit the program")
}
@Override
public void run() {
while(true)
{
try{
Thread.sleep(3 * 1000);
}catch(InterruptedException e){}
if(autoSave)
autoSave();
}
}
private void autoSave() {
System.out.println ("The job file has been automatically saved."");
}
}
If it hadn't been t.setDaemon(true);
here, we would have kept going in an infinite loop.
© 2024 OneMinuteCode. All rights reserved.