简体   繁体   English

在多线程中在java中工作的同步块

[英]Synchronized block working in java in multithreading

I have one question regarding the post Synchronized block not working , the following code is printing “Hello Java” ….我有一个关于 post Synchronized block not working 的问题,下面的代码正在打印“Hello Java”……。 20 times for obj1 and obj2. obj1 和 obj2 20 次。 This code is similar to that one given in the post.此代码类似于帖子中给出的代码。

As per the explanation, shouldn't the following code also have varying output?根据解释,下面的代码不应该也有不同的输出吗? Can someone please help me to understand the difference between the two?有人可以帮我理解两者之间的区别吗?

class ThreadDemo implements Runnable 
{ 
    String x, y; 
    public void run() 
    { 
        for(int i = 0; i < 10; i++) 
            synchronized(this) 
            { 
                x = "Hello"; 
                y = "Java"; 
              System.out.print(x + " " + y + " ");
            } 
    }

    public static void main(String args[]) 
    { 
        ThreadDemo run = new ThreadDemo (); 
        Thread obj1 = new Thread(run); 
        Thread obj2 = new Thread(run); 
        obj1.start(); 
        obj2.start(); 
    } 
}

You are printing only x and y which are in synchronized block so it's printing the same value.您只打印synchronized块中的xy ,因此它打印相同的值。 Add i which is the outside synchronized block ,in print and you would see varying output.添加i这是外部synchronized块,在打印中,您会看到不同的输出。

class ThreadDemo implements Runnable 
{ 
    String x, y; 
    public void run() 
    {
        for(int i = 0; i < 10; i++) 
            synchronized(this)
            {
                x = "Hello";
                y = "Java";
              System.out.println(x + " " + y + " "+i);
            }
    }
    public static void main(String args[]) 
    { 
         ThreadDemo run = new ThreadDemo (); 
        Thread obj1 = new Thread(run); 
        Thread obj2 = new Thread(run); 
        obj1.start(); 
        obj2.start(); 
    } 
}

You're obtaining a lock on the instance of ThreadDemo on which that run() method is being called.您正在获取对调用 run() 方法的 ThreadDemo 实例的锁定。 Since both threads are using the same object the Synchronized block is working here.由于两个线程都使用相同的对象,因此 Synchronized 块在这里工作。

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

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