import java.awt.*;
import javax.swing.*;
public class ThreadTest1 extends JFrame implements Runnable
{
private static final long serialVersionUID = 1L;
private Thread thread1,thread2;
private int x1=-100;
private int x2=-50;
public ThreadTest1()
{
super("多线程1");
setSize(400,300);
setBackground(Color.white);//设置背景颜色
thread1=new Thread(this);
thread2=new Thread(this);
thread1.start();
thread2.start();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void panit(Graphics g)
{
Graphics2D cmp2D=(Graphics2D)g;
cmp2D.setColor(getBackground());
cmp2D.fillRect(0,0, getSize().width, getSize().height);//清除面板
cmp2D.setColor(Color.BLUE);
cmp2D.drawOval(x1, 100, 50, 50);//绘制矩形
cmp2D.setColor(Color.GREEN);
cmp2D.drawOval(x2, 200, 50, 50);//绘制圆形
}
public void run()//实现Runnable接口的方法run()
{
while(true)
{
if(Thread.currentThread()==thread1)//如果当线程为Thread1则执行以下代码
{
x1+=6;
if(x1>=500)
x1=-100;
repaint();
pause(100);//线程休眠100ms
}
else if(Thread.currentThread()==thread2)//如果当线程为Thread2则执行以下代码
{
x2 +=4;
if(x2>=500)
x2=-50;
repaint();
pause(120);//线程休眠120ms
}
}
}
private void pause(int time)//设定线程休眠时间
{
try
{
Thread.sleep(time);
}
catch(InterruptedException e)
{}
}
public static void main(String[] args)
{
new ThreadTest1();
}
}
public void paint(Graphics g)
@Override
public void panit(Graphics g) {
...
}