public class TestTreadClose { public static volatile boolean flag = true; public static void main(String[] args) throws Exception { Thread t = new Thread() { @Override public void run() { int i = 0; while (flag) { i++; System.out.println(i); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); // break; } } } }; // t.setDaemon(true); //这个是可以的 t.start(); Thread.sleep(2000); // t.interrupt(); //这个要配合catch中的break // t.destroy(); //这个要配合catch中的break // t.stop(); //这个是可以的 // flag=false; // 这个是可以的 } }
可行的方式
1 用一个static volatile变量控制
2 设置线程的demon属性为true
3 使用stop方法,不过这个api是不建议使用的