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

📄 expthread2.java

📁 java关于多线程的课堂练习
💻 JAVA
字号:
/**
 * @(#)ExpThread2.java
 *
 *
 * @author 
 * @version 1.00 2007/12/1
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class Bird extends Thread {
 private int xdir=2*(1-2*(int)Math.round(Math.random()));
 private int ydir=2*(1-2*(int)Math.round(Math.random()));
 private boolean running=false;
 private Cage cage=null;
 protected int x,y;
 public Bird(Cage c,int x,int y) {
  cage=c;
  this.x=x;
  this.y=y;
  start();
 }
 public void start() {
  running=true;
  super.start();
 }
 public void halt() {
  running=false;
 }
 public void run() {
  while (running) {
   move();
   try {
   	sleep(120);
   }
   catch (InterruptedException ie) {
   	System.err.println("Thread interrupted");
   }
   cage.repaint();
  }
 }
 private void move(){
 	x+=xdir;
 	y+=ydir;
 	if (x>cage.getSize().width) {
 	 x=cage.getSize().width;
 	 xdir*=(-1);
 	}
 	if (x<0)  xdir*=(-1);
 	if (y>cage.getSize().height) {
 	  y=cage.getSize().height;
 	  ydir*=(-1);
 	}
 	if (y<0)  ydir*=(-1);
 }
 public void draw(Graphics g) {
  g.drawImage(cage.bird,x,y,30,40,cage);
 }
}
class Cage extends JFrame implements ActionListener {
 private JButton  quit=new JButton("Quit");
 private JButton  start=new JButton("Start");
 private JButton  stop=new JButton("Stop");
 private Bird  birds[]=new Bird[20];
 Image  bird=Toolkit.getDefaultToolkit().getImage("bird.jpg");
 public Cage() {
  setLayout(new FlowLayout());
  add(quit);
  quit.addActionListener(this);
  add(start);
  start.addActionListener(this);
  add(stop);
  stop.addActionListener(this);
  
  setSize(300,300);
  setVisible(true);
  validate();
  
  for (int i=0; i<birds.length; i++) {
  	int x=(int)(getSize().width*Math.random());
  	int y=(int) (getSize().height*Math.random());
  	birds[i]=new Bird(this,x,y);
  }
 }
 public void actionPerformed(ActionEvent ae) {
  if (ae.getSource()==stop) 
  	 for (int i=0; i<birds.length; i++) 
  	   birds[i].halt();
  if (ae.getSource()==start)
  	 for (int i=0; i<birds.length; i++) {
  	  birds[i].halt();
  	  birds[i]=new Bird(this,birds[i].x,birds[i].y);
  	 }
  if (ae.getSource()==quit) 
  	System.exit(0);
 }
 public void paint(Graphics g) {
  for (int i=0; i<birds.length; i++) 
  	if (birds[i]!=null)
  	  birds[i].draw(g);
 }
}




public class ExpThread2 {
        
    /**
     * Creates a new instance of <code>ExpThread2</code>.
     */
    public ExpThread2() {
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
       new Cage();
    }
}

⌨️ 快捷键说明

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