一个线程问题
请看如下代码:
Count.java:
public class Count {
private int num;
public void count() {
for(int i = 1; i <= 10; i++) {
num += i;
}
System.out.println(Thread.currentThread().getName() + "-" + num);
}
}
我们期望每次输出的结果值都是55
ThreadTest.java:
public class ThreadTest {
public static void main(String[] args) {
Runnable runnable = new Runnable() {
Count count = new Count();
public void run() {
count.count();
}
};
for(int i = 0; i < 10; i++) {
new Thread(runnable).start();
}
}
}
这里启动了10个线程,看一下输出结果:
Thread-0-55
Thread-1-110
Thread-2-165
Thread-4-220
Thread-5-275
Thread-6-330
Thread-3-385
Thread-7-440
Thread-8-495
Thread-9-550
请问不应该都是55吗
------解决方案--------------------
10个线程使用一个count对象,每个线程都去调用同一个count对象的count方法,都会使得count对象的成员变量num增加,所以每个线程输出的num可能是不一样的