有人可以向我解释为什么静态sychonised代码返回此结果?

时间:2016-02-12 11:30:04

标签: java multithreading oop static

public class Threads9Main
{

    public static void main(String[] args) 
    {
        Threads9 thread1 = new Threads9("Thread1");
        Threads9 thread2 = new Threads9("Thread2");
        Threads9 thread3 = new Threads9("Thread3");
        Threads9 thread4 = new Threads9("Thread4");
        Threads9 thread5 = new Threads9("Thread5");
        Threads9 thread6 = new Threads9("Thread6");
        Threads9 thread7 = new Threads9("Thread7");
        Threads9 thread8 = new Threads9("Thread8");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
        thread6.start();
        thread7.start();
        thread8.start();
    }
}

public class Threads9 extends Thread
{   

public Threads9(String paramName)
    {
        name = paramName;
    }
    private static String name;

    public void run() 
    {
        print();
    }

    private static synchronized void print() 
    {
        for(int i = 0;i<10;i++)
        {
            System.out.println(name+ " looping");
            System.out.println(i);
        }
    }
}

以下是我结果的前5行:

Thread8 looping
Thread8 looping
Thread8 looping
Thread8 looping
Thread8 looping

为什么它只显示thread8而不显示thread1-7?

2 个答案:

答案 0 :(得分:0)

问题在于:

private static String name;

这意味着只有一个name字段,它是static,这意味着它在对象的所有实例之间共享。

答案 1 :(得分:0)

静态字段属于类,并且在该类的所有对象之间共享。在你的情况下

private static String name;

是一个共享字段。 在每个线程创建时,它会覆盖prev值,在启动所有线程之前,name的值为'Thread8'。因此,您会看到它始终打印Thread8