📄 threadtest2.java
字号:
import java.awt.*;
import javax.swing.*;
public class ThreadTest2 extends JFrame implements Runnable
{ //实现Runnable接口
private Thread thread1, thread2; //声明线程对象
private int x1 = 0;
private int y1 = 0;
private int x2 = 0;
private int y2 = 0;
private int t1 = 0;
private int t2 = 0;
public ThreadTest2()
{
super("多线程");
setSize(400,500);
setBackground(Color.WHITE); //设置背景色
//创建两个线程
thread1 = new Thread(this);
thread2 = new Thread(this);
//启动两个线程
thread1.start();
thread2.start();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g)
{
Graphics2D comp2D = (Graphics2D)g;
//填充圆形
comp2D.setColor(Color.BLUE);
comp2D.fillOval(x1, y1, 30, 30);
//填充圆形
comp2D.setColor(Color.GREEN);
comp2D.fillOval(x2, y2, 30, 30);
}
public void run()
{ //实现Runnable接口的方法run()
while(true){
//如果当前线程为thread1则执行以下代码
if(Thread.currentThread() == thread1)
{
t1++;
x1 = 50 + 20 * t1;
y1 = 50 + (int)(1.0/2.0 * 9.8 * Math.pow(t1, 2));
if(y1 >= 450)
t1 = 0;
repaint();
//线程thread1休眠100毫秒
pause(200);
//如果当前线程为thread2则执行以下代码
}
else if(Thread.currentThread() == thread2)
{
t2++;
x2 = 300;
y2 = 50 + (int)(1.0/2.0 * 9.8 * Math.pow(t2, 2));
if(y2 >= 450)
t2 = 0;
repaint();
//线程thread2休眠120毫秒
pause(200);
}
}
}
private void pause(int time) //设定线程休眠时间
{
try
{
Thread.sleep(time);
} catch (InterruptedException e) {}
}
public static void main(String[] args)
{
ThreadTest2 test = new ThreadTest2();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -