我正在做一种研究,其中我想使用户线程作为守护程序线程,Thread.setDaemon(真)使一个线程守护程序,但由于我们knowDaemon线程适合做后台工作,所以我想链接我的这个线程到任何后台守护程序线程,以便我的守护程序线程可以提供一些服务,它应该结束时,该守护程序线程结束时,虽然我已经创建了守护程序线程,但请告诉我如何通过我的守护程序线程提供服务到任何现有的守护程序线程,然后它应该结束最后,请告知。
Thread daemonThread = new Thread(new Runnable(){
@Override
public void run(){
try{
while(true){
System.out.println("Daemon thread is running");
}
}catch(Exception e){
}finally{
System.out.println("Daemon Thread exiting"); //never called
}
}
}, "Daemon-Thread");
daemonThread.setDaemon(true); //making this thread daemon
daemonThread.start();
}发布于 2012-05-06 14:35:50
我不知道你的意思,但我会改变
while(true){至
while(!Thread.currentThread.isInterrupted()){这将允许您的线程在中断时停止。
我还会考虑使用ExecutorService,因为这样可以更容易地将工作传递给另一个线程,并在完成时将其关闭。
ExecutorService service = Executors.newSingleThreadExecutor(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r, "worker");
t.setDaemon(true);
return t;
}
});
service.submit(new Runnable() { /* task for this thread to perform */ });
service.shutdown(); // to stop it.https://stackoverflow.com/questions/10468629
复制相似问题