ublic class TT implements Runnable{
int b=100;
public synchronized void m1() throws Exception{
b=1000;
Thread.sleep(3000);
System.out.println("b="+b);
}
public synchronized void m2()throws Exception{
//Thread.sleep(2500);
b=2000;
}
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();
tt.m2();
System.out.println(tt.b);
}
}
到底是m1()先执行还是m2()先执行啊?结果是多少?各位大侠请具体说明。先感谢大家了。

解决方案 »

  1.   

    这里面有连个线程,一个主线程,一个子线程
    两个线程的优先级是相同的
    所以谁先执行是根据CPU的时间片决定的
      

  2.   

    public class TT implements Runnable {
    int b = 100; public synchronized void m1() throws Exception {
    b = 1000;
    Thread.sleep(3000);
    System.out.println("b=" + b);
    } public synchronized void m2() throws Exception {
    // Thread.sleep(2500);
    b = 2000;
    } 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();
    tt.m2();

    //主线程
    Thread thread = Thread.currentThread();
    thread.setName("主线程");
    System.out.println(thread);//打印结果
    //子线程
    t.setName("子线程");
    System.out.println(t);//打印结果

    System.out.println(tt.b);
    }
    }打印结果:
    Thread[主线程,5,main]
    Thread[子线程,5,main]可以清楚的看到,线程的优先级是相同的
      

  3.   

    看线程启动的速度了
    但大多数情况下,线程启动的速度赶不上main主线程执行的速度,所以是主线程m2被先执行的几率将远远大于m1被先执行的几率
      

  4.   

    不是随机的,自己做过例子测试了,是有先后优先级情况的:
    当子进程的优先级大于main进程时将会输出【b=1000】,否则输出【2000】;
    当子进程和main进程相同的优先级时将会输出【2000】,否则输出【b=1000】,这种情况下main进程优先级高于所有子进程;