Java: mytextarea.setText(“hello”) + Thread.sleep(1000) = strange result

前端 未结 4 1620
清歌不尽
清歌不尽 2020-12-21 11:20

I have something like this:

for(int i=0; i<5; i++){
    mytextarea.setText(\"hello \" + i);
    try{
        Thread.currentThread().sleep(1000); //to give         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-21 11:47

    Another way to not block the Event Dispatch Thread (EDT) is to start a new Thread:

    Thread thread = new Thread(new Runnable() {
        @Override
        public void runt() {
            for (int i=0; i<5; i++) {
                mytextarea.setText("hello " + i);
                try {
                    Thread.sleep(1000); //to give time for users to read
                } catch (InterruptedException e) {
                    break;    // interrupt the for
                }
            }
        }
    });
    thread.start();
    

    EDIT:
    In general Swing is NOT thread safe, that is, Swing methods not marked as thread safe should only be called on the EDT. setText() is thread-safe, so it's no problem in the above code.

    To run a code on the EDT, you use invokeAndWait() or invokeLater() from javax.swing.SwingUtilities (or from java.awt.EventQueue).

    For more details see: Swing's Threading Policy

提交回复
热议问题