11

我的理解: 与 Swing 中对 JComponent.repaint() 的调用中的大多数组件/操作不同,它是线程安全的,即尽管重绘请求是从另一个线程(即不是来自 EDT)发出的,但实际的绘制只发生在 EDT 中。下面的代码片段演示了这一点。

public class PaintingDemo {

    public static void main(String[] args) {
        final JFrame frame = new JFrame();
        final JPanel p = new MyPanel();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                frame.add(p, BorderLayout.CENTER);
                frame.setSize(200, 200);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
        new Thread("MyThread") {
            public void run() {
                while (true) {
                // Below statements are important to show the difference
                    p.repaint();
                    p.paintImmediately(p.getBounds());
                    try {
                        Thread.sleep(1000);
                    } catch(Exception e) {}
                }
            }
        }.start();
    }

}

class MyPanel extends JPanel {
    @Override
    public void paint(Graphics g) {
        System.out.println("paint() called in "+ Thread.currentThread().getName());
        super.paint(g);
    }
}

从输出可知,当调用 repaint() 时,无论从哪个线程调用它,绘画都是在 EDT 中完成的 - 所以没有问题。但是,在 paintImmediately() 的情况下 - 绘画发生在调用它的同一线程中。

考虑这样一种情况,EDT 正在更改组件的状态,而另一个线程(从中调用 paintImmediately())正在绘制相同的组件。

我的问题: 在paintImmediately() 的情况下,事件调度线程(EDT)和其他线程之间的同步是如何处理的?

4

1 回答 1

7

据我了解,当您调用paintImmediately 时,您调用以下代码:

        Component c = this;
        Component parent;

        if(!isShowing()) {
            return;
        }

        JComponent paintingOigin = SwingUtilities.getPaintingOrigin(this);
        if (paintingOigin != null) {
            Rectangle rectangle = SwingUtilities.convertRectangle(
                    c, new Rectangle(x, y, w, h), paintingOigin);
            paintingOigin.paintImmediately(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
            return;
        }

        while(!c.isOpaque()) {
            parent = c.getParent();
            if(parent != null) {
                x += c.getX();
                y += c.getY();
                c = parent;
            } else {
                break;
            }

            if(!(c instanceof JComponent)) {
                break;
            }
    }
    if(c instanceof JComponent) {
        ((JComponent)c)._paintImmediately(x,y,w,h);
    } else {
        c.repaint(x,y,w,h);
    }

因此,除非这不是 a ,否则JComponent您最终会调用_paintImmediately()which 最终会调用paint(Graphics)下面的堆栈跟踪(从我将在本文末尾发布的一段代码中捕获):

Thread [pool-1-thread-1] (Suspended)    
    TestPaint$1.paint(Graphics) line: 23    
    TestPaint$1(JComponent).paintToOffscreen(Graphics, int, int, int, int, int, int) line: 5221 
    RepaintManager$PaintManager.paintDoubleBuffered(JComponent, Image, Graphics, int, int, int, int) line: 1482 
    RepaintManager$PaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1413  
    RepaintManager.paint(JComponent, JComponent, Graphics, int, int, int, int) line: 1206   
    TestPaint$1(JComponent)._paintImmediately(int, int, int, int) line: 5169    
    TestPaint$1(JComponent).paintImmediately(int, int, int, int) line: 4980 
    TestPaint$1(JComponent).paintImmediately(Rectangle) line: 4992  
    TestPaint$3.run() line: 50  
    ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: 1110  
    ThreadPoolExecutor$Worker.run() line: 603   
    Thread.run() line: 722  

但是,如果您尝试同时调用repaint()(从另一个线程),您会看到两者同时运行(我尝试使用调试器单步执行代码,并且绘制从未停止在另一个线程中发生)似乎在 Java 代码级别,没有太多同步(至少我什么都看不到)。所以如果你最终在 EDT 中修改了组件状态,我相信结果是非常不可预测的,你应该尽量避免这种情况。

只是为了说明我的观点,我尝试在paint方法中修改变量的状态,添加一个sleep以增加 2 个线程(EDT 和另一个)之间发生冲突的风险,并且显然这两个线程之间没有同步(不时System.err.println()输出) 。null

现在我想知道为什么你需要立即执行绘画。除非您阻止 EDT,否则没有太多正当理由可以执行此类操作。

下面是我用来测试这些东西的代码(非常接近问题中发布的代码)。该代码仅用于尝试了解正在发生的事情,而不是展示如何执行正确的绘画或任何良好的 Swing 练习。

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import java.util.concurrent.Executors;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class TestPaint {

    protected void initUI() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle(TestPaint.class.getSimpleName());
        final Random rand = new Random();
        final JPanel comp = new JPanel() {
            private String value;

            @Override
            public void paint(Graphics g) {
                value = "hello";
                super.paint(g);
                try {
                    Thread.sleep(20);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                g.setColor(new Color(rand.nextInt(256), rand.nextInt(256), rand.nextInt(256)));
                g.fillRect(0, 0, getWidth(), getHeight());
                if (SwingUtilities.isEventDispatchThread()) {
                    System.err.println("Painting in the EDT " + getValue());
                } else {
                    System.err.println("Not painting in EDT " + getValue());
                }
                value = null;
            }

            public String getValue() {
                return value;
            }
        };
        frame.add(comp);
        frame.setSize(400, 400);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
        Timer t = new Timer(1, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                comp.repaint();
            }
        });
        t.start();
        Executors.newSingleThreadExecutor().execute(new Runnable() {

            @Override
            public void run() {
                while (true) {
                    comp.paintImmediately(comp.getBounds());
                }
            }
        });
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new TestPaint().initUI();
            }
        });
    }

}
于 2012-12-25T22:00:23.607 回答