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();
}
}
}