要求:三个方块,同时出发,改变其在x轴上的位置,来观察其运动的快慢。
代码:
import java.awt.Color; import java.util.Random; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; /** * */ /** * @author: Annie * @date:2016年6月14日 * @description:使用多线程 */ public class Race extends Thread { String ThreadName;//记录线程的名字 JLabel l; JPanel jp1,jp2,jp3;//显示三个矩形 JFrame jf; public Race() { jp1 = new JPanel(); jp1.setSize(20, 20); jp1.setBackground(Color.pink); jp1.setBounds(10, 40, 20, 20); jp2 = new JPanel(); jp2.setSize(20, 20); jp2.setBackground(Color.BLUE); jp2.setBounds(10, 80, 20, 20); jp3 = new JPanel(); jp3.setSize(20, 20); jp3.setBackground(Color.YELLOW); jp3.setBounds(10, 120, 20, 20); l = new JLabel(""); l.setBounds(10, 10, 160, 200); jf = new JFrame("多线程赛跑例子"); jf.setSize(400, 300); jf.setLayout(null); jf.add(l); jf.add(jp1); jf.add(jp2); jf.add(jp3); jf.setVisible(true); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } @Override public void run() { //添加一个判断,如果是第一个线程执行runA,第二个则是RunB,第三个则是RunC; if(Thread.currentThread().getName() .equals("tA")){ runA(); }else if (Thread.currentThread().getName().equals("tB") ){ runB(); }else { runC(); } } //分别控制三个矩形的x坐标 public void runA(){ Random random = new Random(); int s = random.nextInt(200);//随机y坐标 for (int i = -10; i <= 400; i+=2) { jp1.setBounds(i, s, 20, 20); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } public void runB(){ Random random = new Random(); int s = random.nextInt(300);//随机y坐标 for (int i = -10; i <= 400; i+=4) { jp2.setBounds(i, s, 20, 20); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } public void runC(){ Random random = new Random(); int s = random.nextInt(300);//随机y坐标 for (int i = -10; i <= 400; i+=6) { jp3.setBounds(i, s, 20, 20); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { Race r = new Race(); Thread tA = new Thread(r); tA.setName("tA"); tA.start(); Thread tB = new Thread(r); tB.setName("tB"); tB.start(); Thread tC = new Thread(r); tC.setName("tC"); tC.start(); } }
运行效果: