代码在此,他说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);
}
}
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);
}
}
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之前运行,马老师说的没错,马士兵老师讲这里的视频我到没看过,但我觉得这样说没错
你自己调调看
synchronized (TestSync2.class) {
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
int b = 1000;
// synchronized (f2);
System.out.println("B1 = " + b);
}用类来锁定。