創建線程的兩種傳統方式
代碼
package thread;
public class TraditionalThread {
public static void main(String[] args) {
// 第一種 繼承 Thread類
Thread thread = new Thread() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("1 : " + Thread.currentThread().getName());
}
}
};
thread.start();
// 第二種 Runnable接口 這種方式耦合度低, 並且更加符合面向對象的編程思想
// 將線程 和線程所運行的代碼分離 分別放到兩個對象中 使用時在組合起來
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("2 : " + Thread.currentThread().getName());
}
}
});
thread2.start();
new Thread(new Runnable() {
@Override
public void run() {
}
}) {
public void run() {
// 會運行這裏的代碼
// 原因是子類對象重寫了父類中的run方法,而尋找Runnable接口的run方法是在父類run方法重定義的
};
}.start();
}
}
定時器程序
代碼
package TraditionalThread;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class TraditionalTimerTest {
private static int count = 0;
public static void main(String[] args) {
// 炸彈 在程序啓動後過3秒後爆炸 然後再每間隔1秒鐘中爆炸一次
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.out.println("bombing!");
}
}, 3000, 1000);
// 炸彈 在程序啓動後過3秒後爆炸 然後再每間隔2,4,2,4...秒鐘中爆炸一次
class MyTimerTask extends TimerTask {
@Override
public void run() {
count = (count + 1) % 2;
System.out.println("bombing!");
new Timer().schedule(new MyTimerTask(), 2000 + 2000 * count);
}
}
new Timer().schedule(new MyTimerTask(), 3000);
while (true) {
try {
Thread.sleep(1000);
System.out.println(new Date().getSeconds());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}