您的位置:首页 > 其它

一个简单的守护线程示例

2016-03-28 16:28 316 查看
线程有两类:用户线程和守护线程。 用户线程是那些完成有用工作的线程。 守护线程 是那些仅提供辅助功能的线程。Thread 类提供了 setDaemon() 函数。Java 程序将运行到所有用户线程终止,然后它将破坏所有的守护线程。

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Scanner;

/**
* 守护线程<p>
* 示例:
*  主线程 负责 接收键盘输入
*  守护线程 负责 读写操作
*
*  主线程结束时,守护线程是被强制结束。
*      http://www.imooc.com/video/6310/0 */
public class DeamonThreadDemo {
public static void main(String[] args) {
System.out.println("进入主线程"+Thread.currentThread().getName());
DeamonThread deamon = new DeamonThread();
Thread thread = new Thread(deamon);
thread.setDaemon(true);     //设置成守护线程
thread.start();

System.out.println("主线程阻塞中...");
Scanner sc = new Scanner(System.in);
sc.next();
sc.close();

System.out.println("结束主线程"+Thread.currentThread().getName());
}

}

class DeamonThread implements Runnable{

@Override
public void run() {
System.out.println("进入守护线程"+Thread.currentThread().getName());
try {
writerToFile();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("结束守护程"+Thread.currentThread().getName());

}

private void writerToFile() throws Exception{
File file = new File("D:"+File.separator+"测试.txt");
OutputStream os = new FileOutputStream(file,true);
int count = 0;
while(count < 99){
os.write(("\r\nworld"+count).getBytes());
System.out.println("向文件中写入:world"+count++);
Thread.sleep(1000);
}
os.close();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Deamon Thread 守护线程