日期:2014-05-20 浏览次数:20967 次
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class WaitNotifyTest extends JFrame {
private JButton sayHello;
private JButton stop;
private JButton wake;
private boolean flag;
public static void main(String[] args) {
new WaitNotifyTest().launch();
}
public void launch() {
sayHello = new JButton("hello");
stop = new JButton("stop");
wake = new JButton("wake");
flag = true;
add(sayHello);
add(stop);
add(wake);
sayHello.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
while (flag == false) {
synchronized (this) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("hello");
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
flag = false;
}
});
wake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (this) {
flag = true;
this.notify();
}
}
});
this.setLayout(new FlowLayout());
this.pack();
this.setVisible(true);
}
}
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class WaitNotifyTest extends JFrame {
private JButton sayHello;
private JButton stop;
private JButton wake;
private boolean flag;
static Object ob=new Object(); //用于做同步对象锁。
public static void main(String[] args) {
new WaitNotifyTest().launch();
}
public void launch() {
sayHello = new JButton("hello");
stop = new JButton("stop");
wake = new JButton("wake");
flag = true;
add(sayHello);
add(stop);
add(wake);
sayHello.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
new Thread(new Runnable(){ //内部类再创建并启动一个线程
public void run(){
while (flag == false) {
synchronized (WaitNotifyTest.ob) {
try {
WaitNotifyTest.ob.wait(); //不用this了.
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("hello");
}
}).start();
}
});
stop.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
flag = false;
}
});
wake.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
synchronized (WaitNotifyTest.ob) { //这的同步对象也变了。
flag = true;
WaitNotifyTest.ob.notify();
}
}
});
this.setLayout(new FlowLayout());
this.pack();
this.setVisible(true);
}
}