猿问

Java:基础的多线程问题,思路没转过来这个弯

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”才对吧?

守着一只汪
浏览 412回答 1
1回答

紫衣仙女

new Thread的时候使用Runnable作为线程运行的代码 生成了一个新的线程对象new了两次就是创建了两个start了两次分别启动这两个线程的执行
随时随地看视频慕课网APP

相关分类

Java
我要回答