public class DaemonThreadDemo { /** * @param args */ public static void main(String[] args) { System.out.println("进入Main线程 " + Thread.currentThread().getName()); ThreadDaemon daemonThread = new ThreadDaemon(); Thread t1 = new Thread(daemonThread, "DaemonThread1"); t1.setDaemon(true); t1.start(); Scanner sc = new Scanner(System.in); sc.next(); System.out.println("退出Main线程 " + Thread.currentThread().getName()); } } class ThreadDaemon implements Runnable { @Override public void run() { System.out.println("进入守护线程 " + Thread.currentThread().getName()); try { writeToFile(); } catch (Exception e) { e.printStackTrace(); } System.out.println("退出守护线程 " + Thread.currentThread().getName()); } private void writeToFile() throws Exception { File fileName = new File("d:" + File.separator +"JavaDameonThread.txt"); OutputStream os = new FileOutputStream(fileName, true); int count = 0; while(count < 100) { os.write(("\r\nHello Java" + count).getBytes()); System.out.println("守护线程 " + Thread.currentThread().getName() + "向文件中写了 Hello Java " + count++); Thread.sleep(1000); } } }
输完字符后需要回车一下,才能读取。试一下