我创建了JFrame
,其中包含InternalFrame
,它绘制正在移动的图形(每个图形是另一个线程
),我想要 PauseButton
让它暂停,所以我想在传递的对象上同步它们。
但是当我按下暂停按钮时,整个窗口都卡住了,我无法按下播放按钮 另一件事是,当时只有一个正在运行,我希望它们全部运行然后全部暂停。
class A extends JFrame{
....
Object o = new Object();
JButtton pauseButton = new JButton("pause");
JButtton playButton = new JButton("play");
B b = new B(o);
pauseButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (synchronizator) {
try {
synchronizator.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
playButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (synchronizator) {
synchronizator.notifyAll();
}
}
...
}
<小时/>
class B extends JInternalFrame{
Object o;
B(Object o){this.o = o}
./...
many... C thread = new C(o);
....
}
<小时/>
class C extends Thread{
Object o;
booolean running;
public void run(){
while(running){
synchronized(o){
}
}
}
}
最佳答案
不!! ;)
所有 Swing Activity 都应在 AWT 事件调度线程 (EDT) 上完成。使用普通的与线程无关的对象,也许还可以使用javax.swing.Timer
(而不是java.util
!)来计时。
您可能想做其他不涉及不同线程上的 Swing 的事情,但我建议保持真正干净的分离。也就是说很少有对象应该处理线程问题。
如果您使用的是裸露的低级 Java 同步工具,请在 notify
/notifyAll
之前设置一个条件,并放置您的 wait
在 while
循环内。
关于java - 同步传递的对象时,JFrame 卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16335972/