代码:
public class Test implements Runnable {
private int b = 100;
public static void main(String[] args) throws InterruptedException {
Test task = new Test();
Thread thread = new Thread(task);
thread.setName("thread--1");
thread.start();
task.m2();
System.out.println("main thread b=" + task.b);
}
synchronized void m1() throws InterruptedException {
b = 1000;
Thread.sleep(500);
System.out.println("b=" + b);
}
synchronized void m2() throws InterruptedException {
Thread.sleep(250);
b = 2000;
}
@Override
public void run() {
try {
m1();
} catch (Exception e) {
// TODO: handle exception
}
}
}
对于run方法的调用m1(),其实是this.m1(),那this怎么理解:
this用于函数中,代表该函数所在类的当前对象,this所在的函数是run,run对应的类是Test,线程要执行run,实际就是要di 调用task的run,所以是task,从字节码和线程的角度理解如下图: