[英]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.