⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 10+

📁 本压缩文档为《Java大学实用教程》(7-121-00959-5 电子工业出版社 2005.3) 的电子教案。
💻
字号:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Win extends JFrame implements Runnable,ActionListener
{  
   Thread moveOrStop;
   JButton start,hang,resume,die;
   JLabel moveLabel;
   boolean move=false,dead=false;
   Win()
   { 
     moveOrStop=new Thread(this);
     start=new JButton("线程开始");
     hang=new JButton("线程挂起");
     resume=new JButton("线程恢复");
     die=new JButton("线程终止");
     start.addActionListener(this);
     hang.addActionListener(this);
     resume.addActionListener(this);
     die.addActionListener(this);
     moveLabel=new JLabel("线程负责运动我");
     moveLabel.setBackground(Color.red);
     Container con=getContentPane();
     con.setLayout(new FlowLayout());
     con.add(start);
     con.add(hang);
     con.add(resume);
     con.add(die);
     con.add(moveLabel);
     setSize(500,500);
     validate();
     setVisible(true);
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   }
   public void actionPerformed(ActionEvent e)
   {
     if(e.getSource()==start)
       {
         try {
               move=true;
               moveOrStop.start();      //启动线程。
             }
         catch(Exception event)
             {
             }
       }
      else if(e.getSource()==hang)
       {
          move=false;
       }
      else if(e.getSource()==resume)
       {
          move=true;
          resumeThread();               //恢复线程。
       }
      else if(e.getSource()==die)
       {
           dead=true;
       }
   }
   public void run()
   { 
     while(true)
      {
         while(!move)   
           {
             try{
                  hangThread();          //挂起线程。
                }
             catch(InterruptedException e1)
                {
                }
           }
         int x=moveLabel.getBounds().x;
         int y=moveLabel.getBounds().y;
         y=y+2;
         if(y>=200)  y=10;
         moveLabel.setLocation(x,y); 
          try{
               moveOrStop.sleep(200); 
             }
           catch(InterruptedException e2)
             {
             }
         if(dead==true)
           {
              return;      //终止线程。
           } 
      }
   }
  public synchronized void  hangThread() throws InterruptedException
   {
      wait();  
   }
  public synchronized void  resumeThread()
   {
      notifyAll();
   }
} 
public class Example
{
  public static void main(String args[])
  {
     Win win=new Win();
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -