连续线程执行

时间:2011-02-03 09:58:55

标签: java multithreading

任何人都可以帮助我吗?我想在我的项目中连续执行一个线程(比如无限循环)。我想通过XRPC配置文件测试管理连接。

提前致谢。

3 个答案:

答案 0 :(得分:1)

这将执行无限[如果没有错误或异常发生]

new Thread(new Runnable(){public void run(while (true){/*your code*/})}).start();

答案 1 :(得分:1)

首选的Java 1.6方法如下:

Executors.newSingleThreadExecutor().execute(new Runnable(){
    @Override
    public void run(){
        while(true){
            // your code here
        }
    }
});

(虽然它几乎等同于org.life.java的答案)

答案 2 :(得分:0)

使用Lambda并添加停止功能:

    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);
相关问题