繁体   English   中英

在java中用线程显示忙状态

[英]Displaying busy status with thread in java

我正在编写一个Java应用程序,它写入excel表数据集,这需要一段时间才能完成。

我想在你安装东西的时候创建类似于在Linux上编写点到屏幕的东西。

这有可能在java?打印点,而其他线程实际上写入excel,然后在它完成后,一个显示点也退出?

我想打印点到控制台。

@John V.答案的变体是使用ScheduledExecutorService:

// SETUP
Runnable notifier = new Runnable() {
    public void run() {
        System.out.print(".");
    }
};

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

// IN YOUR WORK THREAD
scheduler.scheduleAtFixedRate(notifier, 1, 1, TimeUnit.SECONDS);
// DO YOUR WORK
schedule.shutdownNow();

修改通知程序对象以满足您的个人需求。

它很有可能。 使用newSingleThreadExecutor打印点,而另一个线程进行解析。 例如

ExecutorService e = Executors.newSingleThreadExecutor();
Future f = e.submit(new Runnable(){
   public void run(){
       while(!Thread.currentThread().isInterrupted()){
          Thread.sleep(1000); //exclude try/catch for brevity
          System.out.print(".");
       }
   }
});
//do excel work
f.cancel(true);
e.shutdownNow();

是的,有可能,您可能希望让您的工作线程设置一个变量,以指示它正在工作以及何时完成。 然后通过扩展Thread类或实现Runnable接口来创建一个线程。 这个线程应该无限循环,在这个循环中它应该做你想要它做的任何打印,然后检查变量以查看工作是否完成。 当变量值改变时,打破循环并结束线程。

一个说明。 观察您的处理速度。 如果处理器使用率很高,请在循环内使用Thread.sleep() 这个帖子不应该是劳动密集型的。 System.gc()是另一种使线程等待的流行方法。

不是一个优雅的解决方案,但完成工作。 它在循环中打印1,2,3,1,2 ......点,并在5秒后终止所有内容。

public class Busy {

    public Busy() {
        Indicator i = new Indicator();
        ExecutorService ex = Executors.newSingleThreadExecutor();
        ex.submit(i);
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        i.finished = true;
        ex.shutdown();
    }

    public static void main(String[] args) {
        new Busy();
    }

    private class Indicator implements Runnable {

        private static final int DOTS_NO = 3;
        private volatile boolean finished = false;

        @Override
        public void run() {
            for (int i = 0; !finished; i = (i + 1) % (DOTS_NO + 1)) {
                for (int j = 0; j < i; j++) {
                    System.out.print('.');
                }
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                for (int j = 0; j < i; j++) {
                    System.out.print("\b \b");
                }
            }
        }

    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM