2
試圖做簡單的程序使用線程。但我無法理解一些事情。這裏是我的代碼:我在Java中的線程
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainClass {
public static void main(String[] args) {
new BIGBUTTON();
}}
class GUILCLASS extends Thread {
int i;
public GUILCLASS(){
start();
i=0;
}
@Override
public void run() {
super.run();
while (true){
System.out.println("I did this cycle " +i +" times");
i++;
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class BIGBUTTON extends JFrame {
private JButton buttonForTestingButton;
private JPanel panel1;
GUILCLASS guilclass=new GUILCLASS();
boolean mark1;
public BIGBUTTON() {
panel1=new JPanel();
buttonForTestingButton=new JButton("Button for testing");
mark1=true;
setVisible(true);
setBounds(100,100,100,100);
add(panel1);
add(buttonForTestingButton);
buttonForTestingButton.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
if(mark1){
synchronized (guilclass){
try {
guilclass.wait();
mark1=false;
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
} else {
synchronized (guilclass){
guilclass.notify();
mark1=true;
}
}
}
});
}
}
什麼我'試圖做的是通過點擊按鈕,使一個線程等待(),直到我對這個按鈕再次點擊,但我的按鈕即可凍結,沒有什麼事情發生。尋求幫助。
您可能會佔用導致GUI掛起的Event Dispatch Thread。看看它的[文檔](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html)。 「_事件調度線程的任務必須快速完成;否則,未處理的事件將備份並且用戶界面變得無法響應。」 – Henrik