多线程 - 为什么私有成员变量共享?

use*_*343 0 java multithreading

以下代码的运行在不同时间输出6,7,8.我不知道为什么.每个线程都有count变量,它是私有的.然后他们如何共享相同的变量?

public class ThreadSafety {

    public static void main(String[] args) throws InterruptedException {

        ProcessingThread pt = new ProcessingThread();
        Thread t1 = new Thread(pt, "t1");
        t1.start();
        Thread t2 = new Thread(pt, "t2");
        t2.start();
        //wait for threads to finish processing
        t1.join();
        t2.join();
        System.out.println("Processing count="+pt.getCount());
    }

}

class ProcessingThread implements Runnable{
    private int count = 0;

    @Override
    public void run() {
        for(int i=1; i< 5; i++){
            processSomething(i);
            count++;
        }
    }

    public int getCount() {
        return this.count;
    }

    private void processSomething(int i) {
        // processing some job
        try {
            Thread.sleep(i*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

谢谢

Kay*_*man 6

你有两个线程,但只有一个对象.当然,这些线程将共享单个对象的所有变量.如果您创建了2个ProcessingThread对象并为两个线程提供了自己的实例,则不会发生这种情况.