package com.thread.main;
import org.junit.jupiter.api.Test;
/**
* Created by Administrator on 2017/6/13.
*/
public class MyThread{
@Test
public void main() {
new B().start();
new C().start();
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Home {
private static Home home;
private Home(){}
public static Home getInstance(){
if (home == null) {
synchronized (Home.class) {
home = new Home();
}
}
return home;
}
public static String name;
public synchronized String into(String name1) {
System.out.println(name1+"进来了");
this.name = name1;
if ("张三".equals(name1)) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return name;
}
}
class B extends Thread{
@Override
public void run() {
Home home = Home.getInstance();
System.out.println("B:"+home.into("张三"));
}
}
class C extends Thread{
@Override
public void run() {
Home home = Home.getInstance();
System.out.println("C:"+home.into("李四"));
}
}
打印结果:
张三进来了
李四进来了
C:李四
B:李四
synchronized不是方法同步吗,为什么针对多个线程同时访问的时候会出现这个问题呢,小弟这点没搞懂,请各位解答下,谢谢