我已经开始深入学习线程,并在尝试理解我编写以下代码的概念的同时,我不确定代码的输出。以下是我编写的代码,
public class UnsafeCheck extends Thread {
private static Person person;
// This method is not thread safe without synchronization. Make the method
// synchronized to make the code thread safe.
public synchronized Person getPerson() {
if(person == null) {
System.out.println("Inside if block");
person = new Person("Kilarapu Yethendra", 27);
}
return person;
}
public void run() {
System.out.println("thread's run method");
getPerson();
}
public static void main(String[] args) {
UnsafeCheck uc = new UnsafeCheck();
uc.start();
UnsafeCheck uc1 = new UnsafeCheck();
uc1.start();
UnsafeCheck uc2 = new UnsafeCheck();
uc2.start();
}
}
输出:
线程的运行方法
内部 if 块
线程的运行方法
内部 if 块
线程的运行方法
内部 if 块
如果我们观察到线程 uc 所做的输出更改并没有反映在线程 uc1 中,这就是为什么每个线程控制都转到 if 块的原因。我期望在 uc1 执行 run 方法时初始化 person 引用,但是对于 uc1 线程来说 person 仍然为空。
我所做的一个更有趣的观察是,如果我将 getPerson() 方法设为静态,我将按预期获得输出。以下是 getPerson() 方法为静态时的输出。
输出:
线程的运行方法
内部 if 块
线程的运行方法
线程的运行方法。
请帮助我理解流程。
函数式编程
Cats萌萌
相关分类