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

问题描述 投票:-2回答:2

我对帖子Synchronized block not working有一个问题,以下代码正在打印“ Hello Java”……。 obj1和obj2的20倍。此代码类似于帖子中给出的代码。

根据说明,以下代码也不应该具有不同的输出吗?有人可以帮我了解两者之间的区别吗?

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(); 
    } 
}
java multithreading synchronized
2个回答
3
投票

您仅打印x块中的ysynchronized,因此它打印的是相同的值。在打印中添加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(); 
    } 
}

0
投票

您正在获得在其上调用该run()方法的ThreadDemo实例的锁。由于两个线程都使用同一个对象,因此同步块在这里工作。

© www.soinside.com 2019 - 2024. All rights reserved.