public class MyThread extends Thread {
public void run(){
.... //要在线程里运行的代码
}
}
public class MyThread implements Runnable {
public void run(){
... //要在线程里运行的代码
}
}
public class ThreadTest extends Thread {
public static void main(String[] args) {
//主线程开始
System.out.println("主线程开始。。。。。");
//子线程开始
new ThreadTest().start();
//在主线程运行一此代码
Thread t = Thread.currentThread();
for(int i=0; i<10; i++){
System.out.println("我是"+t.getName()+",我的id是"+t.getId());
}
}
@Override //在子线程中执行的代码
public void run() {
Thread t = Thread.currentThread();
for(int i=0; i<10; i++){
System.out.println("我是"+t.getName()+",我的id是"+t.getId());
}
}
}运行的结果是不唯一的,多个线程执行,每时每刻线程都在抢着工作,抢一点工作一点,直到线程结束为止。那么线程什么时候算是停止了呢?这要了解一下线程的生命周期。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingRect extends JPanel implements Runnable {
private int x = 10;
private int y = 10;
public static void main(String[] args) {
//设置窗口属性。
JFrame frame = new JFrame();
frame.setSize(800, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(250, 50);
frame.add(new MovingRect());
frame.setVisible(true);
}
public MovingRect() {
//设置面板属性
this.setSize(800, 600);
this.setLocation(10, 10);
//创建子线程,并让它进入就绪状态。
Thread t = new Thread(this);
t.start();
this.setVisible(true);
}
@Override
public void paint(Graphics g) {
super.paint(g);
Color c = g.getColor();
g.setColor(Color.RED);
//画一个方块
g.fillRect(x, y, 15, 15);
g.setColor(c);
}
//子线程要做的就是更改方块的位置坐标,并刷新。
public void run() {
while (true) {
this.x += 8;
this.y += 6;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.repaint();
}
}
}
837



被折叠的 条评论
为什么被折叠?



