Java中的多线程排序动画



所以我正在编写一个程序,使用折线图类型的东西来动画化插入排序算法。按照现在的编写方式,当点击填充按钮时,它将生成一个随机的整数数组,并根据代表线绘制DrawingPanel,当点击暂停按钮时,会冻结大约5秒,然后显示排序后的图形。我想显示每个迭代,每次显示一行移动。任何建议。我真的不知道如何在Java中使用多线程,我是个新手。如果有任何建议,我将不胜感激。

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import javax.swing.*;
import java.util.Random;
import java.util.Arrays;
public class AnimationApplication extends JFrame {
private static final long serialVersionUID = 1L;
AnimationPanel panel1 = new AnimationPanel();
AnimationPanel panel2 = new AnimationPanel();
public static void main(String[] args) {
    AnimationApplication prog = new 
     AnimationApplication("Animation Application");
    prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    prog.setSize(450, 300);
    prog.setVisible(true);
}
AnimationApplication(String title) {
    super(title);
    setLayout(new BorderLayout());
    add(panel1, BorderLayout.WEST);
    add(panel2, BorderLayout.EAST);
}
}
class AnimationPanel extends JPanel implements ActionListener, Runnable {
private static final long serialVersionUID = 1L;
private int currentSize;
private JButton populate = new JButton("Populate Array");
private JButton pauseB = new JButton("Pause");
private JButton stopB = new JButton("Stop");
private DrawingPanel drawingCanvas = new DrawingPanel();
private volatile Thread animator = null;
private volatile boolean animationSuspended = false;
ArrayList<Integer> pointList = new ArrayList<Integer>();
private Integer [] rndInts;
AnimationPanel() {
    setLayout(new BorderLayout());
    JPanel buttonP = new JPanel(new GridLayout(1, 3, 5, 5));
    buttonP.add(populate);
    buttonP.add(pauseB);
    buttonP.add(stopB);
    populate.addActionListener(this);
    pauseB.addActionListener(this);
    stopB.addActionListener(this);
    add(drawingCanvas, BorderLayout.CENTER);
    add(buttonP, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == populate) {
                        rndInts = new Integer[ getSize().width-1];

                        for(int i = 0; i < rndInts.length; i++)
  {
    Random rand = new Random();
    rndInts[i]=rand.nextInt((getSize().height)-1);
  //  System.out.println(rndInts[i]);
  }
  currentSize = rndInts.length;               
       pointList = new ArrayList<Integer>(Arrays.asList(rndInts));                

        //System.out.println("Start button pressed");
        // Check if no animation thread exists
        if (animator == null) {
            // If not, start the animation
            start();

        } else {
            // If animation is paused, resume it
            if (animationSuspended) {
                resume();
            }
        }
    } else if (e.getSource() == pauseB) {
        insertionSort(rndInts , currentSize);
        // Check if animation thread exists
        if (animator != null) {
            // If so, suspend the animation thread
            animationSuspended = true;
        }
    } else if (e.getSource() == stopB) {
        stop();
        clear();
    }
}
public void run() {
    Thread thisThread = Thread.currentThread();
    drawingCanvas.repaint();
    while (animator == thisThread) {
        //System.out.println("Animation thread running");
      drawingCanvas.repaint();
        try {
          //  Thread.sleep(1);
 drawingCanvas.repaint();
            if (animationSuspended) {
                synchronized (this) {
                    while (animationSuspended && animator == thisThread) {
                        drawingCanvas.repaint();
                        wait();
                        drawingCanvas.repaint();
                    }
                }
            }
        } catch (InterruptedException e) {
            break;
        }
        // Repaint the panel
        drawingCanvas.repaint();
    }
}
public void start() {
drawingCanvas.repaint();
    // Create a new animation thread and start it
    animator = new Thread(this);
    animationSuspended = false;
    animator.start();
    animationSuspended = true;
 }


public synchronized void stop() {
    drawingCanvas.repaint();
    animator = null;
    notify();
}
public synchronized void resume() {
    animationSuspended = false;
    notify();
}
public void clear() {
    pointList.clear();
    repaint();
}

void insertionSort(Integer [] arr, int length) 
{
  int i, j, tmp;
  for (i = 1; i < length; i++) 
{
        j = i;
        while (j > 0 && arr[j - 1] > arr[j]) 
{
              tmp = arr[j];
              arr[j] = arr[j - 1];
              arr[j - 1] = tmp;
              j--;
              stop();
              drawingCanvas.repaint();
              start();
              //resume();
        }
  }
}

class DrawingPanel extends JPanel implements Runnable {
    private static final long serialVersionUID = 1L;
    protected void paintComponent(Graphics g) {


        // Call superclass version of method
        super.paintComponent(g);
        this.setBackground(Color.WHITE);
        //clear the background
        g.clearRect(0, 0, getSize().width-1, getSize().height-1);
        g.setColor(Color.RED);

        // Draw points
        for (int i = 0; i < currentSize ; i++) //pointList.size(); i++) 
        {
          g.drawLine(i, getSize().height, i, rndInts[i]);
          repaint();
            //resume(); 
        }
      }
    }
}
void insertionSort(Integer[] arr, int length) {
        int i, j, tmp;
        for (i = 1; i < length; i++) {
            j = i;
            while (j > 0 && arr[j - 1] > arr[j]) {
                tmp = arr[j];
                arr[j] = arr[j - 1];
                arr[j - 1] = tmp;
                j--;
                stop();
                drawingCanvas.repaint();
                start();
                // resume();
            }
        }
    }

我认为这段代码就是问题所在,在一个循环中,start();被调用了好几次。请调试并了解如何重构。

一些建议:

1.)你不需要(更特别的是,不要想要)多线程(Thread)。

2.)所有对Swing方法(我认为repaint除外)的访问都必须在事件队列上。(事实上,根据个人经验,Swing在99.999%的时间内对EventQueue运行良好,但0.001%是谋杀!)即使没有线程,你的main方法在事件队列上也是而不是,所以开始这样的操作:

EventQueue.InvokeLater( new Runnable()  {
    AnimationApplication prog = new AnimationApplication( "Animation Application" );
    prog.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    prog.setSize(450, 300);
    prog.setVisible(true);
} );

3.)使用Swing计时器来完成每一步。用"填充"按钮启动它,用"暂停"按钮暂停它(如果可以,停止它,如果不能,重新创建它,我已经有一段时间没有用过了,我的记忆力很差)。Swing计时器与您可以使用的任何其他计时器(如AWT计时器)不同,它在EventQueue上运行其事件。

4.)编写一个执行排序一步的方法。然后在每个计时器事件中调用它一次,因此在每个事件中执行排序一步骤,然后更新显示。

更一般地说,您必须使您的显示工作在UI事件(按钮按下和计时器事件)之外,而不是当前排序代码的进度。你的排序需要从内到外,按照UI的节奏跳舞,而不是尽可能快地进行排序。如今的代码执行速度太快,一个线程无法观察另一个线程在做什么。

最新更新