我的代码有问题。我试图在两个线程中执行两个简单的 GUI 框架(仅用于测试目的)。我想使用 wait()
等待线程并使用 notify()
进行通知或notifyAll()
第二个线程。我也用过synchronized()
并且没有工作。
有人可以非常清楚地向我解释(举例)我做错了什么吗?我是编程新手,对此了解不多。 谢谢 !
这是我的片段:
public void example5() throws InterruptedException {
Thread t = new Thread() {
public final Object obj = new Object();
public void run() {
synchronized(this) { //coordinating activities and data access among multiple threads
//The mechanism that Java uses to support synchronization is the monitor
try {
obj.wait(3000); //suspendarea thread-ului t / punerea in asteptare
} catch (InterruptedException ex) {
}
JFrame frame = new JFrame();
JButton b = new JButton("CLICK ME 1");
JPanel panel = new JPanel();
panel.add(b); frame.add(panel); frame.setBounds(700, 500, 150, 100); frame.setVisible(true);
}
}
};
}
Thread t1 = new Thread(new Runnable() {
public final Object obj = new Object();
public void run() {
obj.notify();
JFrame frame = new JFrame();
JButton b = new JButton("CLICK ME 2");
JPanel panel = new JPanel();
panel.add(b); frame.add(panel); frame.setBounds(700, 500, 150, 100); frame.setVisible(true);
}
});
最佳答案
wait 和notify 应该在同一个对象上调用。试试这个:
Object ob1 = new Object();
Thread t1 = new Thread() {
@Override
public void run() {
try {
System.out.println("ob1 tries to wait in t1...");
synchronized (ob1) {
ob1.wait();
}
System.out.println("ob1 is up in t1!");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
Thread t2 = new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
System.out.println("t2 tries to notify ob1's single waiter...");
synchronized (ob1) {
ob1.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("t2 notified ob1's single waiter!");
}
};
t1.start();
t2.start();
输出:
ob1 尝试在 t1 中等待...
t2 尝试通知 ob1 的单个服务员...
t2通知了ob1的单例服务员!
ob1 已在 t1 中启动!
关于java - 我不明白如何在线程上使用等待和通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32081591/