代码在此,他说F1和F2都被synchronized了,虽然先f1.start().但是后面跟着执行F2();那么必须等F2执行完了,才能执行F1。我就不懂了,F1在F2之前开始执行,为什么不是先锁住F1然后等F1执行完以后再执行F2呢?
public class TestSync2 implements Runnable{
static int b = 10;

public synchronized void f1(){
try{
Thread.sleep(1000);
} catch (InterruptedException ie){}
int b = 1000;
//synchronized (f2);
System.out.println("B1 = " + b);
}

public  synchronized static void f2(){
try{
Thread.sleep(5000);
} catch (InterruptedException ie){}
int b = 2000;
System.out.println("B2 = " + b);
}

public void run(){
f1();
}

public static void main(String[] args){
TestSync2 ts = new TestSync2();
Thread tst = new Thread(ts);
tst.start();
TestSync2.f2();
System.out.println("ALL DONE B= " + ts.b);
}
}

解决方案 »

  1.   

    代码是不是有问题,f2是static的,f1是非static的,两个方法锁的对象不一样,互相并不影响
      

  2.   


     public  synchronized static void f2(){
             try{
             System.out.printl("运行f2");
             Thread.sleep(5000);
         }    catch (InterruptedException ie){}
             int b = 2000;
             System.out.println("B2 = " + b);
              }         
    把方法f2()加这行代码,看看,f2是在什么时候执行的,就知道了;
    下面是测试类public class Test{
      public static void main(String arg0[]){
         Class.formName("TestSync2");
      }
    }我这里在网吧,不方便调试,如果没错的话,上面“运行f2”,会打出来,这说明静态代码是在类加载的时候执行的,所以方法f2在f1之前运行,马老师说的没错,马士兵老师讲这里的视频我到没看过,但我觉得这样说没错
    你自己调调看
      

  3.   

    上面打错了,应该是Class.forName("TestSync2");
      

  4.   

    ++,但是确实是方法f2()方法先执行的,7楼说的也不对,静态块才是类加载的时候执行,这是静态方法,应该是类加载的时候“编译”好(这块不懂,坐等大牛解释),程序顺序执行到start方法时,会创建新的新线程,并执行run方法(这个过程需要花费时间),主函数继续顺序执行,所以f2会先执行(因为中间没有其他代码,如果中间执行时间足够长f1会先执行),果然想满足f2锁定f1不执行的话,f1方法需要改成
    synchronized (TestSync2.class) {
        try {
    Thread.sleep(1000);
        } catch (InterruptedException ie) {
        }
    int b = 1000;
    // synchronized (f2);
    System.out.println("B1 = " + b);
     }用类来锁定。