📄 threadtest.java
字号:
package thread;
import java.awt.*;
import javax.swing.*;
//实现Runnable接口
public class ThreadTest extends JFrame implements Runnable {
private Thread thread1, thread2;
private int x1 = -100;
private int x2 = -50;
public ThreadTest(){
super("多线程");
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 paint(Graphics g){
Graphics2D comp2D = (Graphics2D)g;
comp2D.setColor(getBackground());
//清除画板
comp2D.fillRect(0,0,getSize().width,getSize().height);
//绘制矩形
comp2D.setColor(Color.BLUE);
comp2D.drawRect(x1, 100, 50, 50);
//绘制圆形
comp2D.setColor(Color.GREEN);
comp2D.drawOval(x2, 200, 50, 50);
}
//实现Runnable接口的方法run()
public void run(){
while(true){
//如果当前线程为thread1则执行以下代码
if(Thread.currentThread() == thread1){
x1 += 6;
if(x1 >= 500)
x1 = -100;
repaint();
//线程thread1休眠100毫秒
pause(100);
//如果当前线程为thread2则执行以下代码
} else if(Thread.currentThread() == thread2){
x2 += 4;
if(x2 >= 500)
x2 = -50;
repaint();
//线程thread2休眠120毫秒
pause(120);
}
}
}
//设定线程休眠时间
private void pause(int time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) { }
}
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -