java中多线程使用问题

danwell7 2011-12-23 07:29:18
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的最初位置啊?

...全文
102 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
danwell7 2011-12-29
  • 打赏
  • 举报
回复
谢了,试一下
西部流云 2011-12-24
  • 打赏
  • 举报
回复
你应该使用wait和notify方法进行通信,而不是使用sleep方法。
dongchao_mygirl 2011-12-23
  • 打赏
  • 举报
回复
这个应该是main函数的主线程分的时间片内已经执行过了,没有显示吧
Oo伍oO 2011-12-23
  • 打赏
  • 举报
回复

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧