关于java线程的问题

来源:百度知道 编辑:UC知道 时间:2024/07/03 01:21:18
public class TT implements Runable{
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 = 1000;
}

public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}

public static void main(String[] args) throw exception{
TT tt = new TT();
Thread t = new Thread(tt);
t.start();

tt.m2();
System.out.println(tt.b);
}
}

请问一下谁知道这个执行过程啊?? 为什么执行结果是1000 b = 1000啊?? 还有就是为什么不是先执行m1方法呢?

因为m2睡眠时间比m1短,所以m2先睡醒,这时b的值已经被m1修改为1000,所以打印出1000.
接着m1睡醒,然后打印b=1000;

其实有时候也有一个时间片问题,也许有时候是mian方法一直占用CPU,也许等执行到t.start()方法时,新线程就抢到了时间片,所以这是不稳定的.

还有就是多线程中,main方法不会等其他方法返回,它会接着一直往下执行.

既然是线程嘛,就是异步的,一进到start方法就不管它了,马上返回接着执行main的其他语句

先执行m1,但是由于sleep,所以main中执行m2,然后输出b。
说是在的b并没有被锁定。