如何使用Thread.sleep在for循环中添加延迟?

时间:2015-01-30 11:27:04

标签: java multithreading timer

我需要在for循环中的每次第i次迭代后加一个延迟。问题是我可能无法使用Timer,因为我需要使用参数ck,这取决于之前的迭代。

我尝试使用Thread.sleep(DELAY),但它只是延迟了整个for循环的执行。

    double c = 3;
    int k = 1;  

    for (int j = 0; j<sumJ; j++)
    {
        for (int i=0; i<sumI; i++)
        {
            //...calculations based on values of c and k 
            // received in previous iterations
            try {
                Thread.sleep(100);
            } catch(InterruptedException ie) {}
        }
    }

1 个答案:

答案 0 :(得分:0)

好的,这是使用计时器的一个非常简单的例子。请注意,这是我们正在使用的javax.swing.Timer,这很重要,因为它确保工作在事件线程中完成,即应该对组件进行所有更改。

基本上,我们创建表并显示它,然后,仍然在主线程中,我们准备数据。最后,我们启动计时器,它每半秒触发一次动作事件,从我们准备的数据中填入下一个值。

请注意,当表格填满时,您可以使用GUI,调整大小,选择单元格等。

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.Timer;

class SimpleTest implements ActionListener{

    public static final int ROWS = 10;
    public static final int COLS = 10;
    public static final int DELAY = 500;

    private Integer[][] data = null;
    private int currCol;
    private int currRow;
    private JTable tableToFill = null;
    private Timer theTimer = null;

    /**
     * Calculates the data that should be displayed in the table.
     * In this case it's a simple multiplication table.
     */
    public void fillData() {
        data = new Integer[ROWS][COLS];
        for ( int row = 0; row < ROWS; row++ ) {
            for ( int col = 0; col < COLS; col++) {
                data[row][col] = (row + 1) * (col + 1);
            }
        }
    }

    /**
     * Creates a GUI table to fill up.
     * @return The table object created.
     */
    public JTable setUpJTable() {
        tableToFill = new JTable(ROWS,COLS);
        return tableToFill;
    }

    /**
     * Starts the timer that fills the values in the GUI table
     */
    public void startTimer() {
        if ( tableToFill != null && data != null ) {
            currCol = 0;
            currRow = 0;
            theTimer = new Timer( DELAY, this);
            theTimer.start();
        }
    }

    /**
     * Called by the timer to set the value in the table.
     * 
     * @param evt Action event (not used)
     */
    public void actionPerformed(ActionEvent evt) {
        synchronized (this) {
            if ( currRow < ROWS ) {
                tableToFill.setValueAt(data[currRow][currCol], currRow, currCol);
                currCol++;
                if ( currCol == COLS ) {
                    currCol = 0;
                    currRow++;
                }

            } else {
                theTimer.stop();
            }
        }
    }

    public static void main(String[] args) {

        SimpleTest tableFiller = new SimpleTest();
        JTable table = tableFiller.setUpJTable();

        // Display the table

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(new BorderLayout());
        frame.getContentPane().add(table.getTableHeader(), BorderLayout.PAGE_START);
        frame.getContentPane().add(table, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);

        // Fill the data, then start displaying it gradually

        tableFiller.fillData();
        tableFiller.startTimer();
    }


}