Continuous thread execution
Can any one help me? I want to execute a thread continuously (like infinite loop) in my project. I want to test the admin connections through the XRPC profile.
Thanks in advanc开发者_如何学JAVAe.
this will execute infinite [if no errors or exception occours]
new Thread(new Runnable(){public void run(while (true){/*your code*/})}).start();
The preferred Java 1.6 way to do this is the following:
Executors.newSingleThreadExecutor().execute(new Runnable(){
@Override
public void run(){
while(true){
// your code here
}
}
});
(Although it's almost equivalent to org.life.java's answer)
Using Lambda and adding stop functionality:
AtomicBoolean stop = new AtomicBoolean(false);
Executors.newSingleThreadExecutor().execute(()->{
while(!stop.get()){
System.out.println("working");
}
});
Thread.sleep(5);
System.out.println("Stopping");
stop.set(true);
精彩评论