用Java的Thread、Runnable、Timer三种方法实现每隔一毫秒打印Hello,同时计算从1加到10000,算完后输出结果并停止打印Hello。
一、Thread实现
//打印Hello
package thread;
public class PrintHello extends Thread {
public static boolean flag=true;//标志位:根据标志位判断是否要执行打印
private String str;
public PrintHello() {}
public PrintHello(String str) {
this.str=str;
}
@Override
public void run() {
while(flag){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(str);
}
}
//关闭线程
public void shutdown(){
flag=false;
}
}
//计算从1加到100000。计算完成后输出结果,并关闭PrintHello线程。
package thread;
public class Calculation extends Thread {
int sum=0;
@Override
public void run() {
for(int i=1;i<=10000;i++){
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();

这篇博客通过Thread、Runnable、Timer三种方式在Java中实现每毫秒打印Hello,同时后台计算1到10000的和,计算完成输出结果并停止打印。详细代码示例分别展示了线程类、实现Runnable接口以及使用Timer类的用法。
5834

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



