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

时间:2011-12-31 17:22:17

标签: java multithreading oop concurrency

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();
    }

}

以上测试产生以下输出

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

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

由于

修改

oops ..我忘了包含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());
        }
    }
}

1 个答案:

答案 0 :(得分:5)

你的线程在任何String对象上都没有同步,更不用说同一个了,所以我不确定这个想法来自哪里。由于此行中的RunnableThread关键字,它们已在synchronized对象上自动同步:

public synchronized void runMe(){

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

现在,如果你真的想锁定那个全局String对象,那么该方法看起来像

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

最好制作str final