罗曼零
2015-11-27 19:20
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); } } }
输完字符后需要回车一下,才能读取。试一下
细说多线程之Thread VS Runnable
55327 学习 · 68 问题
相似问题