本帖最后由 黄小贝 于 2013-11-3 23:35 编辑
喔霍霍~让我来拯救世界~~用join呀~~直接上代码~~
大家可以自己跑一下~~十个文件依次上传~~- import java.awt.BorderLayout;
- import java.awt.FlowLayout;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import javax.swing.*;
- public class TestProgress extends Thread implements ActionListener {
-
- private static JProgressBar progressBar;
-
- JFrame jf = new JFrame("Test");
- JPanel jp = new JPanel();
- JTextArea jta = new JTextArea();
- JButton jb = new JButton("点击");
-
- public static void main(String[] args) {
- new TestProgress();
- }
- public TestProgress() {
- jp.setLayout(new FlowLayout());
- progressBar = new JProgressBar();
- progressBar.setValue(0);
- progressBar.setStringPainted(true);
-
- jf.add(jp, BorderLayout.NORTH);
- jf.add(new JScrollPane(jta));
- jp.add(progressBar);
- jp.add(jb);
- jf.add(new JScrollPane(jta), BorderLayout.CENTER);
- jb.addActionListener(this);
- jf.setSize(300, 200);
- jf.setLocation(300, 200);
- jf.setVisible(true);
- jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }
-
- @Override
- public void run() {
- for (int i = 0; i < 10;i++) {//10个文件
- UpLordTread lordTread = new UpLordTread(progressBar,jta,"文件" + i);
- lordTread.start();//启动上传程序
- try {
- lordTread.join();//这就是关键~~等待这个线程完成
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public void actionPerformed(ActionEvent e) {
- String comm = e.getActionCommand();
- if ("点击".equals(comm)) {
- this.start();//不能在EDT线程里面执行费时的操作,防止UI卡死
- jb.setEnabled(false);
- }
- }
- }
- /**
- * 文件上传线程
- * @author yellowbaby
- *
- */
- class UpLordTread extends Thread{
-
- JTextArea jta;
- JProgressBar progressBar;
-
-
- public UpLordTread(JProgressBar progressBar,JTextArea jta,String fileName) {
- super(fileName);
- this.jta = jta;
- this.progressBar = progressBar;
- }
- public void run() {
- for (int i = 0; i <= 100; i++) {
- progressBar.setValue(i);
- String temp = Thread.currentThread().getName() + ":" + i + "\n";
- jta.append(temp);
- try {
- Thread.sleep(10);
- } catch (Exception ee) {
- ee.printStackTrace();
- }
- }
- progressBar.setValue(0);
- }
-
- }
复制代码 有几个知识点说一下
(1)join方法的作用,等待线程死去,当线程调用其他线程的join方法的时候线程会被阻塞,知道那个线程的run跑完,这样就可以解决十个文件依次上传的问题
(2)JProgressBar 是 java自带的进度条,我也是查了才知道,目测当progressBar的value被改变的时候会自动刷新界面,我没有验证,可以找到progressBar所有的valueChange监听看源码就可以知道了
(3)不要在EDT线程里面调用I/O操作,那样UI会卡死,什么是EDT线程自行谷歌,actionPerformed方法是在EDT里面跑的,有什么事情丢给背后线程去完成,我这里的背后线程就是this.start().......
|