线程并发 - 使用字符串对象的锁进行同步

zig*_*ggy 0 java oop concurrency multithreading

class ZiggyTest{

    public static void main(String[] args){

        RunnableThread rt = new RunnableThread();

        Thread t1 = new Thread(rt);
        Thread t2 = new Thread(rt);
        Thread t3 = new Thread(rt);

        t1.start();
        t2.start();
        t3.setPriority(10);
        t3.start();

        try{
            t3.join();
            t2.join();
            t1.join();

            System.out.println("Joined");
        }catch(InterruptedException e){System.out.println(e);}


        Thread t4 = new Thread(new RunnableThread());
        Thread t5 = new Thread(new RunnableThread());
        Thread t6 = new Thread(new RunnableThread());

        t4.start();
        t5.start();
        t6.start();
    }

}
Run Code Online (Sandbox Code Playgroud)

上述测试产生以下输出

Thread-0
Thread-0
Thread-0
Thread-0
Thread-0
Thread-2
Thread-2
Thread-2
Thread-2
Thread-2
Thread-1
Thread-1
Thread-1
Thread-1
Thread-1
Joined
Thread-3
Thread-3
Thread-4
Thread-4
Thread-3
Thread-4
Thread-5
Thread-4
Thread-3
Thread-4
Thread-5
Thread-3
Thread-5
Thread-5
Thread-5
Run Code Online (Sandbox Code Playgroud)

我不明白为什么最后三个线程没有像前三个线程一样使用String对象作为共享锁.即使最后三个线程使用的是'RunnableThread'的不同实例,也不应该同步它们,因为字符串常量池中只有一个'str'副本?

谢谢

编辑

哎呀..我忘了包含RunnableThread.

class RunnableThread implements Runnable{

    String str = "HELLO";

    public void run(){
        runMe();
    }

    public synchronized void runMe(){
        for (int a : new int[]{1,2,3,4,5}){
            System.out.println(Thread.currentThread().getName());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ern*_*ill 5

你的线程不会在任何String对象上同步,更不用说同一个了,所以我不确定这个想法来自何处.RunnableThread由于synchronized此行中的关键字,它们在对象本身上同步:

public synchronized void runMe(){
Run Code Online (Sandbox Code Playgroud)

RunnableThread为最后三个线程使用单独的对象意味着它们独立运行.

现在,如果您确实想要锁定该全局String对象,则该方法将如下所示

public void runMe(){
    synchronized (str) {
        for (int a : new int[]{1,2,3,4,5}){
            System.out.println(Thread.currentThread().getName());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个好主意str final.