1.线程:
线程是彼此互相独立的、能独立运行的子任务,并且每个线程都有自己的调用栈。众所周知,每个java程序都至少有一个线程——主线程。当一个java程序启动时,JVM会创建主程序,并在该线程中调用程序的main()方法。线程,也可以理解为“程序内部一个独立的运行单位”。
2.线程的创建方法:
线程的创建有两种方式:
1.继承java.lang.Thread类
public class TestThread extends Thread{
//重写run方法
public void run(){
}
}
2. 实现java.lang.Runnable接口。
public class TestThreadimplements Runnable {
public void run() {
//重写
}
}
3.启动线程:
线程的启动要调用start()方法
import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class jframe extends JFrame { static jframe jf; public static void main(String[] args) { jf = new jframe(); jf.initUI(); } public void initUI() { this.setSize(600, 500); this.setDefaultCloseOperation(3); this.setLayout(new FlowLayout()); this.setVisible(true); JButton btn = new JButton("开始"); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { thread td = new thread(jf); td.start(); } }); this.add(btn); } } import java.awt.Color; import java.awt.Graphics; import javax.swing.JFrame; public class thread extends Thread { JFrame jf; int X = 0; // X坐标 int Y = 0; // Y坐标 int moveX = 2; // X轴位移 int moveY = 3; // Y轴位移 int width; int height; Graphics g; public thread(JFrame jf) { this.jf = jf; } public void run() { init(); while (true) { try { Thread.sleep(10);// 线程暂停10毫秒,减少CPU使用率 } catch (Exception E) { } g.setColor(jf.getBackground()); g.fillRect(X, Y, width, height); X = X + moveX;// 重新计算X、Y坐标 Y = Y + moveY; // 碰到边界时改变递增值造成反弹效果 if (X >= (width - 30)) { X = width - 30; moveX = -moveX; } if (X <= 0) { X = 0; moveX = -moveX; } if (Y >= (height - 30)) { Y = height - 30; moveY = -moveY; } if (Y <= 0) { Y = 0; moveY = -moveY; } // g.setColor(Color.WHITE); // g.fillRect(X, Y, 30, 30); g.setColor(Color.BLACK); g.fillOval(X, Y, 30, 30); } } public void init() { g = jf.getGraphics(); width = jf.getWidth(); height = jf.getHeight(); } }