简体   繁体   English

Java同步

[英]java synchronized

The Class X have two methods: test and test1 . X类有两种方法: testtest1

I've created two threads: t1 and t2 . 我创建了两个线程: t1t2 Thread t1 is accessing test method and t2 is accessing test1 method of same object. 线程t1正在访问test方法,线程t2正在访问同一对象的test1方法。 When t1 is accessing test method which synchronized it acquires lock on object. t1正在访问同步的test方法时,它将获取对象的锁定。

Will t2 be able to access test1 method on same object? t2可以访问同一对象上的test1方法吗? Why it is able to access this method if t1 has a lock on it? 如果t1上有锁,为什么它能够访问此方法?

If I'm executing the following code 如果我正在执行以下代码

            X x = new X();
           new MyThread(x).start(); // It execute test() method
       new MyThread1(x).start();// It execute test1() method





class X 
{
    String a  = "varsha";
    public synchronized void test ()
    {
        try 
        {
            Thread.sleep (6000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace ();
        }
    } 
    public void test1 ()
    {
        synchronized (a)
        {
        }
    } 
}

You have two different locks: 您有两个不同的锁:

  • test() locks this ; test()锁定了this
  • test1() locks this.a . test1()锁定this.a

The two locks are completely independent and thus the two methods can be called at the same time. 这两个锁是完全独立的,因此可以同时调用这两种方法。

Your code is equivalent to the following: 您的代码等效于以下内容:

class X 
{
    String a  = "varsha";
    public void test ()
    {
        synchronized (this)
        {
            try
            {
                Thread.sleep (6000);
            }
            catch (InterruptedException e) 
            {
                e.printStackTrace();
            }
        }
    } 

    public void test1 ()
    {
        synchronized(a)
        {
        }
    } 
}

So these methods are synchronizing at different objects ( this versus a ) and thus can be executed concurrently without locking each other. 因此,这些方法在不同的对象( thisa )上进行同步,因此可以同时执行而不会彼此锁定。

Note, that I replaced Thread.currentThread ().sleep (6000) with Thread.sleep (6000) because method sleep is static and thus you don't need any instance of Thread in order to use it. 请注意,我将Thread.currentThread ().sleep (6000)替换为Thread.sleep (6000)因为方法sleep是静态的,因此不需要任何Thread实例即可使用它。

class X {

  String a  = "varsha";

   public synchronized void test(){

   try {             
                  //if you are modifying the instance variable here
                  // then the test1() synchronized block will 
                 //not be given lock permission to t2 thread
                 // synchronization is for thread safety.

                 // In your example you are not modifying the instance variable.

   } catch (InterruptedException e) {
    e.printStackTrace();
   }
 } 
 public  void test1(){
   synchronized(a){
   }
 } 
}

Here is whats actually happening. 这是实际发生的事情。
Every object in Java has a "monitor lock", In this case object "x". Java中的每个对象都有一个“监视锁”,在这种情况下为对象“ x”。

There are two threads (MyThread and MyThread1) trying to acquire this lock in the following sequence - 有两个线程(MyThread和MyThread1)试图按以下顺序获取此锁-

Imagine there is a queue – MyThread is in front of MyThread1 in this queue because you have started MyThread first followed by MyThread1. 想象有一个队列–该队列中MyThread在MyThread1的前面,因为您先启动MyThread,然后再启动MyThread1。

MyThread acquires the lock first and it starts executing, you have invoked the sleep() method on it. MyThread首先获取锁,然后开始执行,您已经在其上调用了sleep()方法。 This will change the state of MyThread from "execution state" to "waiting state" and then to "ready state", it will release the lock at this moment since it is not in execution state. 这会将MyThread的状态从“执行状态”更改为“等待状态”,然后更改为“就绪状态”,由于它不在执行状态,因此此时将释放锁。 At this point MyThread1 is ahead in the queue and it acquires the lock and starts executing. 此时,MyThread1在队列中处于前面,它获取了锁并开始执行。

This is in a way similar to the concept of "Context Switch". 这与“上下文切换”的概念类似。 Refer book - Operating System Internals and Design. 参考书-操作系统内部和设计。

When you mark a method as synchronized, it locks the object for that method; 当您将某个方法标记为已同步时,它将锁定该方法的对象; meaning no other thread can access that PARTICULAR method for that object. 意味着没有其他线程可以访问该对象的那个PARTICULAR方法。 In your case no other thread can access the test method; 在您的情况下,没有其他线程可以访问测试方法。 but of course test1 method can be accessed. 但是当然可以访问test1方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM