public class TestThread implements Runnable{
    int b = 0;
public  synchronized void  f1(){
 b =3000;
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("b:"+b);
}
    public  synchronized void f2(){
   
   try {
     Thread.sleep(2500);
   } catch (InterruptedException e) {
     e.printStackTrace();
   }
      b = 2000;
    }
    public void run(){
   f1();
    }
   public static void main(String[] args){
   
   TestThread tt = new TestThread();
   Thread t = new Thread(tt);
   t.start();
   tt.f2();
   System.out.println(tt.b);
   }}
////
这个关于锁的问题是来源与马士兵的视频~~~按照他给我的理解是都有锁时,主线程的先进行,然后子线程。
但不理解的是t.start()优先于System.out.println(tt.b); 
结果是  1000;
        b:1000;但是我修改了子线程的休眠时间比如改为15000时,数据就变了啊
结果是   2000
         b:1000;

解决方案 »

  1.   

    照你的程序看,t.start();这步开启线程需要时间,字面上看是t线程先获得锁(其实不是),其实在开启线程这段时间里,由于主线程调用了f2(),获取了锁,所以t线程阻塞。
      

  2.   


    public class TestThread implements Runnable {    int b = 0;
        public synchronized void f1() {
            System.out.println("f1() 获得锁 --> b: " + b);
            b = 3000;
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("f1() 释放锁 --> b: " + b);
        }    public synchronized void f2() {
            System.out.println("f2() 获得锁 --> b: " + b);
            try {
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            b=2000;
            System.out.println("f2() 释放锁 --> b: " + b);
        }    public void run() {
            f1();
        }    public static void main(String[] args) {
            TestThread testThread = new TestThread();
            Thread t = new Thread(testThread);
            t.start();
            testThread.f2();
            System.out.println("main() --> b: " + testThread.b);
        }
    }
    好好体会吧。。
      

  3.   

    你的看上去很清楚,但我还是不明白。谁先执行的,已经当锁释放后,子线程为什么没立即执行,而打印了System.然后去执行了子线程
      

  4.   


    先输出了System,是因为主线程(main)抢到了CPU, 你在System.out... 前加一句 Thread.sleep(1) 睡1毫秒, 子线程就先抢到了CPU,线程具有不定性,抢占CPU具有不确定性,, 还是建议看看线程的几个状态是怎么转换