题目
- 一个线程运算1+2+3+4+5+6+…+19+20要求此线程每隔0.1秒进行一次累加计算 ,而另一个线程没隔0.1秒读取前一个线程的运算结果
代码
public class Exam1 {
public static void main(String[] args) {
Result result = new Result();
result.sum = 0;
new Thread(new Addition(result)).start();
new Thread(new Output(result)).start();
}
}
class Result {
int sum = 0;
}
class Output implements Runnable {
Result result;
public Output(Result result) {
this.result = result;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(100);
System.out.println(Thread.currentThread().getName() + "获取的值为" + result.sum);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Addition implements Runnable {
Result result;
int count = 1;
public Addition(Result result) {
this.result = result;
}
public void sum() {
for (int i = 1; i <= 19; i++) {
result.sum = result.sum + i;
}
}
@Override
public void run() {
while (true) {
sum();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}