求教下面Java 程序中synchronized的含义和作用
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Suspend extends Applet {
private TextField t=new TextField(10);
private Button
suspend=new Button("Suspend"),
resume=new Button("Resume");
class Suspendable extends Thread{
private int count =0;
private boolean suspended=false;
public Suspendable(){
start();
}
public void fauxSuspend(){
suspended=true;
}
public synchronized void fauxResume(){
suspended=false;
notify();
}
public void run(){
while(true){
try{
sleep(100);
synchronized(this){
while(suspended)
{
wait();
}
}
}catch(Exception e){}
t.setText(Integer.toString(count++));
}
}
}
private Suspendable ss=new Suspendable();
public void init(){
add(t);
suspend.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
ss.fauxSuspend();
}});
add(suspend);
resume.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
ss.fauxResume();
}});
add(resume);
}
public static void main(String[] args) {
Suspend applet = new Suspend();
Frame aFrame = new Frame("Suspend");
aFrame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
aFrame.add(applet, BorderLayout.CENTER);
aFrame.setSize(300,100);
applet.init();
applet.start();
aFrame.setVisible(true);
}
}
?
[code=java][/code]
[解决办法]
synchronized 加锁!当它用来修饰一个方法或者一个代码块的时候,能够保证在同一时刻最多只有一个线程执行该段代码。 也就是说在多线程环境下,保证同一时刻只能有一个线程操作fauxResume方法!
[解决办法]
wait是释放锁的,他吧锁释放后,别人就可以进去了
然后你把synchronized去掉后,因为notify方法执行时一定要获取锁,没有锁的时候执行会抛出EXCEPTION