开发者

Continuous thread execution

开发者 https://www.devze.com 2023-02-08 20:28 出处:网络
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.

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);
0

精彩评论

暂无评论...
验证码 换一张
取 消