本文介绍了什么是Java监视器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java的并发编程中引用的监视器是什么?



当我读到每个对象都关联一个监视器

是否是一个特殊对象?

解决方案


线程1:



b

  public void a()
{
synchronized(someObject){
// do something(1)
}
}

主题2:


$ b b

  public void b()
{
synchronized(someObject){
//做其他事情(2)
}
}

这可以防止线程1和线程2同时访问受监视。一个将开始,监视将阻止另一个在第一个完成之前访问该区域。



这不是一个特殊的对象。它是类层次结构根中的同步机制: java.lang.Object



还有 wait 通知方法也将使用对象的监视器在不同线程之间通信。


What's a monitor referred to in concurrent programming in Java?

When I read that "every object has associated a monitor" what does it meaning?

Is it a special object?

解决方案

A monitor is mechanism to control concurrent access to an object.

This allows you to do:

Thread 1:

public void a()
{
    synchronized(someObject) {
        // do something (1)
    }
}

Thread 2:

public void b()
{
    synchronized(someObject) {
        // do something else (2)
    }
}

This prevents Threads 1 and 2 accessing the monitored (synchronized) section at the same time. One will start, and monitor will prevent the other from accessing the region before the first one finishes.

It's not a special object. It's synchronization mechanism placed at class hierarchy root: java.lang.Object.

There are also wait and notify methods that will also use object's monitor to communication among different threads.

这篇关于什么是Java监视器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 03:37