窗口一个button,点击后执行一个复杂的运算。这个等待时间太长了,所以我决定加一个进度条。找到了一些线程的代码,在主程序体中定义线程,这个线程里去更新窗口中的进度条的值(窗口的frame是定义在这个主程序里,并且定义一个全局变量来表示当前进度,线程获得全程变量的值然后用它更新进度条)。然后在上面的那个按钮的点击事件中,开始时先生成这个线程,在接下来的具体任务中,在不同步骤给这个全局变量设不同的值,直到最后完成.想象中一点击按钮,线程生成了之后就会开始监视全局变量的值,然后同时更新进度条.可实际发现,线程开始执行之后就等在那里,等着我那个点击事件里的具体任务完全作完了,才开始继续去更新进度条.这样也失去我用进度条的意义了.请问大家是怎么回事?谢谢!
我用stepper.start();来启动线程,可是发现线程并没有立即开始工作(这里就是希望进度条一点点增加),而是等当前的函数体(main中的事件处理程序中的那个while的循环)完全执行完毕后)才开始执行线程的具体任务。while循环只是个例子,我要执行的实际是个更复杂的花费时间的任务,所以希望用线程来控制进度条.但实际线程总是这块的任务完成了才执行,就失去用线程的意义了.怎么回事涅?
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.reflect.*; public class ProgressSample { static class BarThread extends Thread {
private static int DELAY = 500;
JProgressBar progressBar; public BarThread(JProgressBar bar) {
progressBar = bar;
} public void run() {
int minimum = progressBar.getMinimum();
int maximum = progressBar.getMaximum();
Runnable runner = new Runnable() {
public void run() {
int value = progressBar.getValue();
progressBar.setValue(value+1);
}
};
for (int i=minimum; i<maximum; i++) {
try {
SwingUtilities.invokeAndWait(runner);
// Our task for each step is to just sleep
Thread.sleep(DELAY);
} catch (InterruptedException ignoredException) {
} catch (InvocationTargetException ignoredException) {
}
}
} }
public static void main(String args[]) {
// Initialize
final JProgressBar aJProgressBar = new JProgressBar(0, 100);
final JButton aJButton = new JButton("Start");
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
aJButton.setEnabled(false);
Thread stepper = new BarThread(aJProgressBar);
stepper.start();
//线程应该从这里开始 int x = -10000000;
while(x < 1000000000){
x ++;
}//线程实际从现在才开始执行 }
};
aJButton.addActionListener(actionListener);
JFrame theFrame = new JFrame("Progress Bars");
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = theFrame.getContentPane();
contentPane.add(aJProgressBar, BorderLayout.NORTH);
contentPane.add(aJButton, BorderLayout.SOUTH);
theFrame.setSize(300, 100);
theFrame.show();
}
}
int x = -10000000;
while(x < 1000000000){
x ++;
} 在这段循环中隔段时间sleep()试试
你繼承Thread類,在BarThread的run里再開一個runnable,錯了吧?
int x = 0;
while(x < 100000){
x ++;
sleep(10);
}