用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);<