【问题标题】:How to create a threaded console progress bar in Java?如何在 Java 中创建线程控制台进度条?
【发布时间】:2018-03-07 06:05:35
【问题描述】:

我正在尝试用 Java 创建一个工作进度条程序,以便它可以同时支持控制台和 GUI 应用程序。

这个想法是使用线程来提供当前的进度信息,但似乎线程代码运行得不好。并发对我来说太新鲜了。

我希望它在每次增加 1 时都将进度条向前推进,而不是在进度条赶上之前过早地完成循环。我猜是时间问题?

[=====>                                            ] 10%  1
2
3
4
5
6
7
8
9
10

[==================================================] 100%  

谁能告诉我我哪里出错了?

主要代码

package console;
import java.util.ArrayList;
import console.ProgressThread;

public class ConsoleProgressBar
{
    private static final long REFRESH_DELAY = 50;
    private ProgressValue progress;
    private ProgressThread target;
    private Thread thread;

    protected static class ProgressValue
    {
        protected long total = 0;
        protected long current = 0;

        protected ProgressValue(long n)
        {
            total = n;
        }

        protected synchronized void setMaxTotal(long n)
        {
            total = n;
        }

        protected synchronized void stepBy(long n)
        {
            current = current + n;

            if (current > total) total = current;
        }

        protected synchronized void stepTo(long n)
        {
            current = n;

            if (current > total) total = current;
        }

        protected synchronized long getCurrent()
        {
            return current;
        }

        protected synchronized long getTotal()
        {
            return total;
        }
    }

    public ConsoleProgressBar(long totalItem)
    {
        this(totalItem, REFRESH_DELAY);
    }

    public ConsoleProgressBar(long totalItem, long refreshDelay)
    {
        progress = new ProgressValue(totalItem);
        target = new ProgressThread(progress, refreshDelay);
    }

    public void start()
    {
        thread = new Thread(target);
        thread.start();
    }

    public void stepBy(long n)
    {
        progress.stepBy(n);
    }

    public void stepTo(long n)
    {
        progress.stepTo(n);
    }

    public void step()
    {
        progress.stepBy(1);
    }

    public void setMaxTotal(long n)
    {
        progress.setMaxTotal(n);
    }

    public void stop()
    {
        target.terminate();

        try
        {
            thread.join();
        }

        catch (InterruptedException ex)
        {
        }
    }

    public long getCurrent()
    {
        return progress.getCurrent();
    }

    public long getTotal()
    {
        return progress.getTotal();
    }

    public static void main(String[] args)
    {
        ArrayList<Integer> test = new ArrayList<>();
        ConsoleProgressBar bar = new ConsoleProgressBar(10, 50);

        bar.start();

        for (int i = 0; i < 10; i++)
        {
            int sum = i + 5;

            test.add(sum);

            bar.step();

            System.out.format("%s%n", bar.getCurrent());
        }

        bar.stop();
    }
}

线程代码

package console;

import console.ConsoleProgressBar.ProgressValue;

public class ProgressThread implements Runnable
{
    private static final int WIDTH = 50;
    private volatile boolean terminated;
    private ProgressValue progressRef;
    private long timeMS;

    public ProgressThread(ProgressValue ref, long refreshDelay)
    {
        progressRef = ref;
        timeMS = refreshDelay;
        terminated = false;
    }

    private void refreshProgressBar()
    {
        StringBuilder sb = new StringBuilder("\r[");
        int percent = (int) Math.floor(100.0 * progressRef.current / progressRef.total);

        for (int i = 0; i < WIDTH; i++)
        {
            if (i < (percent / 2)) sb.append("=");
            else if (i == (percent / 2)) sb.append(">");
            else sb.append(" ");
        }

        sb.append("] %s  ");

        if (percent >= 100) sb.append("%n");

        System.out.printf(sb.toString(), percent + "%");
    }

    void terminate()
    {
        terminated = true;
    }

    public void run()
    {
        try
        {
            while (terminated == false)
            {
                refreshProgressBar();
                Thread.sleep(timeMS);
            }

            refreshProgressBar();
        }

        catch (InterruptedException exc)
        {
        }
    }
}

【问题讨论】:

  • "console" 支持在 Java 中是非常基本的。你可以做something like this example,它基本使用退格字符来删除以前在控制台中打印的字符。如果您想要更复杂的东西,那么您将不得不使用 Curses 实现之一进行调查

标签: java


【解决方案1】:

为什么你需要一个多线程应用程序,而这只是你想要完成的一项任务?

不过,为了实现您想要的,我建议您将执行完全移到线程类或主类中。

如果主应用程序要运行其他东西,那么理想情况下,您应该将执行放在线程类中。但是在这里我把执行放到主类中。它也可以很容易地进入线程类。

例如,我将ProgressThread 中的run() 编辑成这样,

public void run()
{
    while( terminated )
    {
    }
}

我在 ConsoleProgressBar 中编辑了 main 到这个,

public static void main(String[] args)
{
    ArrayList<Integer> test = new ArrayList<>();
    ConsoleProgressBar bar = new ConsoleProgressBar(10, 50);

    bar.start();

    for (int i = 0; i <= 10; i++)
    {
        int sum = i + 5;

        test.add(sum);

        bar.refreshProgressBar();
        System.out.format( "%s", bar.getCurrent() );
        bar.step();
        bar.sleep( 1000 );
    }

    bar.stop();
}

请注意,我将方法 sleep( int n ) 和 refreshProgressBar() 添加到 bar 以便我可以调用线程方法,类似于您对 bar.start() 和 bar.stop() 所做的操作。

为了清楚起见,我在ProgressThread 中将refreshProgressBar 更改为public 只是为了示例,并添加了以下内容,

void sleep( int n )
{
    try
    {
        Thread.sleep( n );
    }
    catch( InterruptedException ie )
    {
        ie.printStackTrace();
    }
}

以下发给ConsoleProgressBar,

private void sleep( int n )
{
    target.sleep( n );
}

private void refreshProgressBar()
{
    target.refreshProgressBar();

}

输出(每行以一秒的间隔打印)是,

[>                                                 ] 0%  0
[=====>                                            ] 10%  1
[==========>                                       ] 20%  2
[===============>                                  ] 30%  3
[====================>                             ] 40%  4
[=========================>                        ] 50%  5
[==============================>                   ] 60%  6
[===================================>              ] 70%  7
[========================================>         ] 80%  8
[=============================================>    ] 90%  9
[==================================================] 100%  10

不确定这是否是您要寻找的,但我建议将执行放在一个地方。

【讨论】:

  • 感谢您的帮助。是的,将执行放在一个地方是有意义的。我希望从这个多线程应用程序中获得的是使另一个类(任何对象)能够将进度更新(仅值)提供给线程可以访问它的另一个类(即 ProgressValue),读取当前进度数据,然后显示进度条。它会那样工作吗?可能吗?
  • @Trevor。是的,这是可能的。为此,您需要依靠某些条件来显示进度条,而不是让它在固定的时间间隔内显示。在这种方法中,您可能会使用wait()、notify() 或类似类型的同步机制。
猜你喜欢
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 2011-02-12
  • 2016-12-14
  • 1970-01-01
  • 2012-02-13
  • 1970-01-01
  • 2014-09-15
相关资源
最近更新 更多