class Core {
private int value;
public int getSum() {
for (int i = 0; i < 50000000; i++) {
value++;
}
return value;
}
}
public class DemoRunnable implements Runnable{
@Override
public void run() {
Core core = new Core();
int sum = core.getSum();
try {
Thread.sleep(100);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(sum);
}
}
public class Client {
public static void main(String[] args) {
DemoRunnable core = new DemoRunnable();
Thread one = new Thread(core);
Thread two = new Thread(core);
one.start();
two.start();
}
}
这段代码的输出结果为
50000000
50000000
为什么会有两行输出结果呢?虽然创建了两个线程,但是执行的是同一个Runnable的实例,那么应该只输出一个“50000000”才对吧?
1 回答

紫衣仙女
TA贡献1839条经验 获得超15个赞
new Thread的时候使用Runnable作为线程运行的代码 生成了一个新的线程对象
new了两次就是创建了两个
start了两次分别启动这两个线程的执行
添加回答
举报
0/150
提交
取消