我的Java线程
尝试执行使用线程的简单程序。但有些事情我不明白。这是我的密码:我的Java线程,java,multithreading,wait,Java,Multithreading,Wait,尝试执行使用线程的简单程序。但有些事情我不明白。这是我的密码: 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 Th
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;
}
}
}
});
}
}
我想做的是点击按钮,让一个线程等待()直到我再次点击这个按钮,但我的按钮只是冻结了,其他什么都没有发生。正在寻求帮助。您可能想了解
wait()
的工作原理,因为它可以让执行它的线程休眠
基本上,如果你想让你的类睡眠,你必须在run()
方法中的某个地方调用wait()
。最简单的方法是在线程guilclass
中引入一个static对象
,在该对象上设置static boolean sleep
直到收到通知。
按下按钮时必须设置
静态布尔睡眠。您可能正在占用事件调度线程,这会导致GUI挂起。看看它的名字。事件分派线程上的任务必须快速完成;否则,未处理的事件将备份,用户界面将失去响应