如题, 已经对m1方法锁定,b=1000应该就不能被访问了吧
可是运行main 方法,结果是1000 b=1000
按道理应该是100 b=1000 呀?求高人解答public class TT implements Runnable{
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b="+b);
} public void m2(){
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
} public static void main(String[] args) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start(); Thread.sleep(1000);
tt.m2();
}
}
可是运行main 方法,结果是1000 b=1000
按道理应该是100 b=1000 呀?求高人解答public class TT implements Runnable{
int b = 100;
public synchronized void m1() throws Exception{
b = 1000;
Thread.sleep(5000);
System.out.println("b="+b);
} public void m2(){
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
} public static void main(String[] args) throws Exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start(); Thread.sleep(1000);
tt.m2();
}
}
在m1()中将b = 1000;和Thread.sleep(5000);调换顺序就能解决。
当然在高负载的机器上不一定就说明你的程序有问题,有由正确的情况发生。
public class TT implements Runnable {
int b = 100; public synchronized void m1() throws Exception {
b = 1000; // flag-1
Thread.sleep(5000); // flag -2
System.out.println("b=" + b);
} public void m2() {
System.out.println(b);
} public void run() {
try {
m1();
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws Exception {
TT tt = new TT();
Thread t = new Thread(tt);
t.start(); // 该线程是否在 start 后马上运行并不确定。需要根据时间片来决定。(跟操作系统的实现以及硬件有关)
// 所以很有可能这里没有启动线程 t
Thread.sleep(1000); // 当前主线程 sleep 后 t 得到运行。执行 flag-1 处。然后 t 在 flag-2 处 sleep.
tt.m2(); // 主线程比 t 先醒。 运行此处 so 打印 1000
//主线程运行完毕 t 运行 so 打印 b =1000
}
}