public class Black {
String name = "black";
void setName(String name) {
this.name = name;
}
void backgroudSetName() throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
setName("white");
}
};
t.start();
t.join();
System.out.println(name);
}
public static void main(String[] args) throws InterruptedException {
Black black = new Black();
black.backgroudSetName();
}
}
输出:
black
setName其实调用的是设置线程名称的方法
public class Black {
String name = "black";
void setName(String name) {
this.name = name;
}
void backgroudSetName() throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
setName("white");
}
};
t.start();
t.join();
System.out.println("thread.getName = " + t.getName());
System.out.println(name);
}
public static void main(String[] args) throws InterruptedException {
Black black = new Black();
black.backgroudSetName();
}
}
输出结果:
thread.getName = white
black
改造一下,可以在线程内部调用setName方法
public class Black {
String name = "black";
void setName(String name) {
this.name = name;
}
void backgroudSetName() throws InterruptedException {
Thread t = new Thread() {
@Override
public void run() {
Black.this.setName("white");
}
};
System.out.println("black1 = " + Black.this);
t.start();
t.join();
System.out.println("thread.getName = " + t.getName());
System.out.println(name);
}
public static void main(String[] args) throws InterruptedException {
Black black = new Black();
System.out.println("black = " + black);
black.backgroudSetName();
}
}
输出:
black = test.arraylist.Black@2eafffde
black1 = test.arraylist.Black@2eafffde
thread.getName = Thread-0
white
同时我们看到Black.this就是main方法的black对象,我们可能在看一些框架源码的时候会有这种写法。