传统线程技术和定时器的应用

时间:2022-10-06 00:14:27

创建线程的两种传统方式

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

}
}
}