Java Thread 的简单应用

运行界面

Java Thread 的简单应用_第1张图片

程序介绍

在窗口中有两个不同颜色的方块,向右以不同速度移动
这里只使用一个线程达到两个方块都移动的目的,在第一方块的纵坐标赋值的时候,采用了随机赋值的random,并不影响程序。

程序代码

package chapter12;

import java.awt.Color;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;

class RaceFrame extends JFrame {
     
	private JPanel tortoise;
	private JPanel rabbit;
	
	public RaceFrame() {
     
		tortoise = new JPanel();
		tortoise.setBounds(0, 50, 30, 30);
		tortoise.setBackground(Color.GREEN);
		add(tortoise);
		
		rabbit = new JPanel();
		rabbit.setBounds(0, 100, 30, 30);
		rabbit.setBackground(Color.RED);
		add(rabbit);
		
		setTitle("Race Frame");
		setSize(600, 500);
		setLocationRelativeTo(null);
		setLayout(null);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setVisible(true);
		
		new TortoiseThread().start();
		new RabbitThread().start();
	}
	
	private class TortoiseThread extends Thread {
     
		Random random = new Random();
		
		@Override
		public void run() {
     
			while(true) {
     
				if(getContentPane().getBounds().contains(getLocation())){
     
					// 随机产生一个值
					int step = random.nextInt(100);
					tortoise.setLocation(tortoise.getX() + 10, step);
				} else {
     
					break;
				}
				try {
     
					sleep(1000);
				} catch (InterruptedException e) {
     
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
	private class RabbitThread extends Thread {
     
		@Override
		public void run() {
     
			while(true) {
     
				rabbit.setLocation(rabbit.getX() + 20, rabbit.getY());
				try {
     
					sleep(1000);
				} catch (InterruptedException e) {
     
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
	
}

public class ThreadTestDemo {
     

	public static void main(String[] args) {
     
		
		RaceFrame raceFrame = new RaceFrame();

	}

}

你可能感兴趣的:(Java,-,尚硅谷,java,开发语言,后端)