实例;
public class MyThread extends Thread { private int i = 0; public void run() { while (true) { i++; System.out.println("i= " + i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } class TestThread { public static void main(String[] args) throws InterruptedException { MyThread myThread = new MyThread(); myThread.setDaemon(true); //设置为守护线程 myThread.start(); Thread.sleep(3000); System.out.println("我离开thread对象也不再打印了,也就是停止了!"); } }
i= 1 i= 2 i= 3 我离开thread对象也不再打印了,也就是停止了! |