我对帖子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();
}
}
您仅打印x
块中的y
和synchronized
,因此它打印的是相同的值。在打印中添加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();
}
}
您正在获得在其上调用该run()方法的ThreadDemo实例的锁。由于两个线程都使用同一个对象,因此同步块在这里工作。