多线程 对比定时器有什么优势

2025-01-21 06:00:16
推荐回答(1个)
回答1:

java Thread类实现定时调度,可以延迟几秒之后再执行,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25

public class ceshi {
public static void main(String[] args) throws Exception {
// run in a second
final long timeInterval = 1000;
Runnable runnable = new Runnable() {
@Override
public void run() {
while (true) {
// ------- code for task to run
System.out.println("Hello !!");
// ------- ends here
try {
Thread.sleep(timeInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
Thread thread = new Thread(runnable);//线程创建
thread.start();//线程启动

}