Java测试守护线程的代码
2017-02-21 15:23
471 查看
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Scanner;
class DaemonThread 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());
}
void writeToFile() throws Exception{
File filename = new File("D:"+File.separator + "daemon.txt");
OutputStream os = new FileOutputStream(filename,true);
int count = 0;
while(count<999){
os.write(("\r\nword"+count).getBytes());
System.out.println("守护线程"+Thread.currentThread().getName()+
"向文件中写入了word"+count++);
Thread.sleep(1000);
}
}
}
public class DaemonThreadDemo {
public static void main(String[] args) {
System.out.println("程序进入了主线程"+Thread.currentThread().getName());
DaemonThread daemonThread = new DaemonThread();
Thread thread = new Thread(daemonThread);
thread.setDaemon(true);
thread.start();
Scanner sc = new Scanner(System.in);
sc.next();
System.out.println("退出主线程"+Thread.currentThread().getName());
}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.Scanner;
class DaemonThread 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());
}
void writeToFile() throws Exception{
File filename = new File("D:"+File.separator + "daemon.txt");
OutputStream os = new FileOutputStream(filename,true);
int count = 0;
while(count<999){
os.write(("\r\nword"+count).getBytes());
System.out.println("守护线程"+Thread.currentThread().getName()+
"向文件中写入了word"+count++);
Thread.sleep(1000);
}
}
}
public class DaemonThreadDemo {
public static void main(String[] args) {
System.out.println("程序进入了主线程"+Thread.currentThread().getName());
DaemonThread daemonThread = new DaemonThread();
Thread thread = new Thread(daemonThread);
thread.setDaemon(true);
thread.start();
Scanner sc = new Scanner(System.in);
sc.next();
System.out.println("退出主线程"+Thread.currentThread().getName());
}
}
相关文章推荐
- java代码线程压力测试
- Java代码测试线程死锁 用jvisualvm监控
- [Java] DaemonThread(守护线程)简介---finally内的代码不一定会被执行
- Java线程测试,输出当前运行的代码所属的线程
- 什么是java的守护线程
- Jsp/Java代码分离.实现页面真正的代码分离 测试代码是否按想法运行,下载原代码
- 用Java线程获取优异性能(II)——使用同步连载线程访问关键代码部份
- 用Java线程获取优异性能(II)——使用同步连载线程访问关键代码部份
- Rsa加密的Java测试代码
- jar完整性测试的Java代码
- java测试代码
- java 守护线程(Daemon)
- 用Java线程获取优异性能(II)——使用同步连载线程访问关键代码部份
- java动态代理类,测试,实现AOP,在执行target回调方法前后插入相关代码处理
- jar完整性测试的Java代码收藏
- Java连接oracle测试代码
- 测试Java代码的执行时间
- 用Java线程获取优异性能(II)——使用同步连载线程访问关键代码部份
- 用Java线程获取优异性能(II)——使用同步连载线程访问关键代码部份
- java 守护线程(Daemon)