一段代码如下
public class T implements Runnable{
int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(5000);
System.out.println("b = " +b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("ab = " +b);//被注释掉的语句
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
T tt = new T();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
运行结果如下
ab = 2000
tt = 2000
b = 1000
可是把句m2()方法这句注释掉//System.out.println("ab = " +b);
结果就有点郁闷,
按理说 tt = 2000的。
可是运行结果是 tt = 1000.
这事怎么回事????
public class T implements Runnable{
int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(5000);
System.out.println("b = " +b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("ab = " +b);//被注释掉的语句
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
T tt = new T();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
运行结果如下
ab = 2000
tt = 2000
b = 1000
可是把句m2()方法这句注释掉//System.out.println("ab = " +b);
结果就有点郁闷,
按理说 tt = 2000的。
可是运行结果是 tt = 1000.
这事怎么回事????
]public class T implements Runnable{
int b = 100;
public synchronized void m1() throws Exception {
b = 1000;
Thread.sleep(5000);
System.out.println("b = " +b);
}
public synchronized void m2() throws Exception {
Thread.sleep(2500);
b = 2000;
System.out.println("ab = " +b);//被注释掉的语句
}
public void run() {
try {
m1();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
T tt = new T();
Thread t = new Thread(tt);
t.start();
tt.m2();
System.out.println(tt.b);
}
}
main线程和你创建的线程,首先是main线程开始运行,在里再创建另一个线程并启动的时候,并不能确定这个线程马上能启动.所以是先执行了m2()方法,把T锁住了,执行完m2后,马上执行System.out.println(tt.b);了,这时候才轮到了T执行m1()方法.
是这句没写好 System.out.println("tt="tt.b);