java multi-threaded daemon thread

The thread is marked as a daemon thread or a user thread. When running thread is a daemon thread, java virtual machine exit.

It must be called before starting the thread.

class StopThread implements Runnable {
    private boolean flag = true;

    @Override
    public  void run() {
        while (flag) {
            System.out.println(Thread.currentThread().getName() + "...run");
        }
    }

    public void changeFlag() {
        flag = false;
    }
}

public class StopThreadDemo {
    public static void main(String[] args) {
        StopThread st = new StopThread();
        Thread t1 = new Thread(st);
        Thread t2 = new Thread(st);
        t1.setDaemon(true);
        t2.setDaemon(true);
        t1.start();
        t2.start();
        int num = 0;
        while (true) {
            if (num++ == 60) {
//                st.changeFlag();
//                t1.interrupt();
//                t2.interrupt();
                break;
            }
            System.out.println(Thread.currentThread().getName() + "......" + num);
        }
        System.out.println("over");
    }
}

Guess you like

Origin www.cnblogs.com/hongxiao2020/p/12612036.html