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{
boolean flag=true; //标志位
@Override
public void run() {
while(flag) {
System.out.println("Hello");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void shutdown() {
flag=false;
}
}
代码涵义就是每隔一秒在界面打印一个Hello,与此同时,程序也在计算1+2+3+。。+10000,算完之后输出。要求:在将加法结果输出之后Hello就不打印了
可最后结果是 输出sum后,依然继续打印hello,并且flag改为false失败
求大佬分析一下