java和同步 [英] java and synchronization

查看:113
本文介绍了java和同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正准备参加SCJP考试,我在完全理解同步方面遇到了麻烦。在第6行,我已经读过在main中运行的线程需要锁定'b'。为什么需要锁定此对象?我的理解是同步的代码块是一个受保护的区域,任何时候只有一个线程可以进入?继续,main中的线程释放此锁并等待'b中的线程完成其run方法。然后'b'中的线程用于通知main中的线程已完成。但是,它看起来并不像是通知任何特定的线程。这个例子来自Sierra和Bates SCJP的书。任何可以在这上面散发的光都会受到赞赏。谢谢

I am preparing for the SCJP exam and I am having trouble with fully understanding synchronization. At line 6, I have read that the thread running in main needs a lock on 'b'. Why does it need a lock on this object? My understanding is that a synchronized block of code is a protected area that only one thread can be in at any time? Moving on,the thread in main releases this lock and waits for the the thread in 'b to complete its run method. The thread in 'b' is then meant to notify the thread in main that it has completed. However, it does not look like it is notifying any specific thread here. This example is from the Sierra and Bates SCJP book. Any light that can be shed on this would be grately appreciated. thanks

class ThreadA {  
    public static void main(String [] args) {  
        ThreadB b = new ThreadB();  
        b.start();  

        **synchronized(b) {  //line 6**
            try {  
                System.out.println("Waiting for b to complete...");  
                b.wait();  
            } catch (InterruptedException e) {}  
                System.out.println("Total is: " + b.total);  
            }  
        }  
    }  
}

class ThreadB extends Thread {     
    int total;  

    public void run() {  
        System.out.println("K");  
        synchronized(this) {  
            for(int i=0;i<100;i++) {  
                total += i;  
            }  
            notify();  
        }  
    }  
}


推荐答案


在第6行,我已经读过在main中运行的线程需要锁定'b'。为什么需要锁定此对象?

At line 6, I have read that the thread running in main needs a lock on 'b'. Why does it need a lock on this object?

因为这就是那条线的作用。它获得了该资源。其他线程可以获得其他同步块,但没有其他线程可以获取该对象的锁定。

Because that is what that line does. It acquires that resource. Other thread can get other synchronized block, but no other thread can acquire a lock on that object.


它看起来不像是在通知这里有任何特定的线程。

it does not look like it is notifying any specific thread here.

这是真的。程序不知道将通知哪个线程,或者即使通知任何线程。您作为开发人员可能会得出结论,有一个特定的线程将被通知,也许是因为它唯一的线程wait()ing。

This is true. The program has no idea which thread will be notify or even if any thread will be notified. You as the developer may conclude there is a particular thread which will be notified, perhaps because its the only thread wait()ing.

这篇关于java和同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆