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

java中多线程使用问题
import java.awt.*;
import java.awt.event.*;

public class BollTest
{
  public static void main(String[] args)
  { Myrame frame=new Myrame();
  frame.setBounds(10, 10, 500, 500);
  frame.setVisible(true);
  frame.addWindowListener(new WindowAdapter(){
  public void windowClosing(WindowEvent e){
  System.exit(0);
  }
  });
  }

}
class Myrame extends Frame implements Runnable
{ Thread 红色球,黄色球;
  MyCanva red ,blue; 
  double t=0;
  Myrame()
  { 红色球=new Thread(this);
黄色球=new Thread(this);  
red=new MyCanva(Color.red);  
blue=new MyCanva(Color.blue);  
setLayout(null);
add(red);
add(blue);
  red.setLocation(60,100);
  blue.setLocation(60,100);  
  红色球.start();
  黄色球.start();
  }
 public void run()
  { while(true)
  { t=t+0.2;
if(t>20)t=0;
if(Thread.currentThread()==红色球) 
{int x=60;
int h=(int)(1.0/2*t*t*3.8)+60;
red.setLocation(x,h);
try
{ 红色球.sleep(50);

}
catch(InterruptedException e){}

}
else if(Thread.currentThread()==黄色球)
{ int x=60+(int)(26*t);
int h=(int)(1.0/2*t*t*3.8)+60;
blue.setLocation(x,h);
try
{ 黄色球.sleep(50);

}
catch(InterruptedException e){}
}
 
  } 
  }
 }
class MyCanva extends Canvas
{ Color c;
  MyCanva(Color c)
  { setSize(20,20);
  this.c=c;
setBackground(Color.gray); 
  }
  public void paint(Graphics g)
  { g.setColor(c);
  g.fillOval(0, 0, 20, 20);
   
  }

}


此程序实现模拟物体自由落体和平抛运动,在红色球.start();黄色球.start();启动线程时,在画布上画得红球和和蓝球的位置没有为先显示为blue.setLocation(60,100)red.setLocation(60,100)的位置,在转到线程方法中red.setLocation(x,h),blue.setLocation(x,h)的位置,而是直接显示为后者的位置,这是为什么??线程使用cpu资源前应该显示 red和blue的最初位置啊?
 


------解决方案--------------------
这个应该是main函数的主线程分的时间片内已经执行过了,没有显示吧