我觉得问题都不在那些地方!!问题在于 public synchronized void m1()     public synchronized void m2() 
这两个涵数的锁都调用的是本类对象BianLiangDemo.class,,就意味着这一同一把锁,,这两个涵不能同步运行,,任何一个函进入后别一个涵数都不能被调用,,,你那个程序中的两个线程生命周期都太短,,看不到效果,,如果把生命周期延长一点,,变成这样:: 
public class BianLiangDemo implements Runnable{ 
        int b=100; 
        public synchronized void m1()throws Exception{ 
                //Thread.sleep(5000); 
                b=1000; 
                                for (int i=0;i<20 ;i++ ) 
                                { 
                                         System.out.println("m1 b="+b); 
                                } 
        } 
        public synchronized void m2() throws Exception{ 
                Thread.sleep(2500); 
                b=2000; 
                                for (int i=0;i<20 ;i++ ) 
                                { 
                                        System.out.println("m2 b="+b); 
                                } 
        } 
        public void run(){ 
                try{ 
                        m1(); 
                }catch(Exception e){e.printStackTrace();} 
        } 
        public static void main(String[] args)throws Exception  { 
                BianLiangDemo t=new BianLiangDemo(); 
                Thread t1=new Thread(t); 
                t1.start(); 
                                //Thread.sleep(10); 
                t.m2(); 
                System.out.println("t="+t.b); 
        } 
} 
你就会发现,,无论Thread.sleep();的值为多少,,System.out.println("m2 b="+b)这个均不能被打印,,因为主函数中的t.m1();一进入m1(),,副线程根本就进不去!! 
如果你想要得到 
m1 b=1000 
m2 b=2000 
t=2000呢? 
可以在t.m2()前面加上Thread.sleep(10):让主线和小睡一会!程序代码就变成了;如下 
public class BianLiangDemo implements Runnable{ 
        int b=100; 
        public synchronized void m1()throws Exception{ 
                //Thread.sleep(5000); 
                b=1000; 
                System.out.println("m1 b="+b); 
        } 
        public synchronized void m2() throws Exception{ 
                //Thread.sleep(2500); 
                b=2000; 
                System.out.println("m2 b="+b); 
        } 
        public void run(){ 
                try{ 
                        m1(); 
                }catch(Exception e){e.printStackTrace();} 
        } 
        public static void main(String[] args)throws Exception  { 
                BianLiangDemo t=new BianLiangDemo(); 
                Thread t1=new Thread(t); 
                t1.start(); 
                Thread.sleep(10); 
                t.m2(); 
                System.out.println("t="+t.b); 
        } 
} 
这样,,其实也没能同步调用函数m1();和m2();因为这两个函数不能同步运行,,这行写只是给点时间,,让副线程先调用m1();副线程调用m1()后,主线程进t.m2(),就不能被调用,处于等待状待,,直到m()运行完后才执行!!,, 
 
这是个人理解,,加上实验得出来的,,不知道对不对,,不过,,我花这么多时间来给你分析这问题,,怎么也给个技术分啊!!谢谢,,纯手打!! |