package com.lzy.thread;
public class PeriodicWork2 extends Thread {
int sum=0;
@Override
public void run() {
for(int i=0;i<=10000;i++) {
sum+=i; //运算1+2+3+....+...+10000的值
if(i%1000==0) {//当i为1000倍数时模拟延迟
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
System.out.println("sum:--->"+sum); //输出1+2+3+。。+。。+10000的值
new Hello().shutdown(); //调用shutdown()方法,关闭打印hello
//System.out.println(new Hello().flag);
}
public static void main(String[] args) {
PeriodicWork2 pw=new PeriodicWork2();
Hello h=new Hello();
Thread t=new Thread(h);
pw.start();
t.start();
}
}
class Hello implements Runnable{
public static boolean flag=true; //标志位
@Override
public void run() {
while(flag) {
System.out.println("Hello");
try {
Thread.sleep(1);//每隔1毫秒打印一次
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void shutdown() {
flag=false;
}
}
现有一个程序,需要每隔一毫秒在界面打印一个“Hello”,与此同时,程序也在计算1+2+3+4+5+..+10000,算完之后输出。要求:在将加法结果输出之后Hello就不在打印
最新推荐文章于 2024-07-13 11:10:40 发布