日期:2014-05-20  浏览次数:20708 次

求教下面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) {