2016-02-26 90 views
0

我實現了一流的下方,得到如下的輸出:的java多線程(在一個類中的兩個同步的方法)

dsfs2000 
2000 
b = 1000; 

我很奇怪,爲什麼它不是:

b = 1000; 
dsfs2000 
2000 

由於t.start()會首先撥打m1()m2()應該等到m1()完成,爲什麼m2()居然先鎖定?

public class TT implements Runnable { 
    int b = 100; 

    public synchronized void m1() throws Exception{ 
     //Thread.sleep(2000); 
     b = 1000; 
     //Thread.sleep(5000); 
     System.out.println("b = " + b); 
    } 

    public synchronized void m2() throws Exception { 

     Thread.sleep(2500); 
     b = 2000; 
     System.out.println("dsfs" + b); 
    } 

    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); 
    } 
} 
+1

你在調用t.start(),它會調用線程的run()方法。在run()方法中,您正在調用m1()。由於線程並行執行,因此您直接調用對象的m2(),因此它先執行,然後執行m1()。您可以預測線程的啓動行爲。如果想驗證延遲,則在調用之間放置sysout.currentTimemilliseconds()。 – Shriram

+0

嘗試在't.start()'和'tt.m2()之間添加'Thread.sleep(1000)'' –

回答

0

在你的代碼

t.start(); // has to go through the overhead of creating a Thread and calling back its `run` 

    tt.m2(); // just calling a method on a already created Object, which is really fast 
0

在你m1()方法在結尾處添加notify();,並在m2()添加wait();在第一,那麼這將是確定。

它是完整的代碼:我已經改變了兩個places.Which是// here

public class TT implements Runnable { 
    int b = 100; 

    public synchronized void m1() throws Exception{ 
     //Thread.sleep(2000); 
     b = 1000; 
     //Thread.sleep(5000); 
     System.out.println("b = " + b); 
     notify(); // here 
    } 

    public synchronized void m2() throws Exception { 
     wait(); // here 
     Thread.sleep(2500); 
     b = 2000; 
     System.out.println("dsfs" + b); 
    } 

    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); 
    } 
} 

評論它是輸出,只要你想:

b = 1000 
dsfs2000 
2000 

解釋:m2()會等到m1()完成工作並通知m2();

0

要回答您的問題:您的main方法在應用程序的主線程中執行。當調用t.start();時,您要求JVM創建一個新線程並執行Runable。這同時發生,也需要一些時間。調用start方法不會阻止主線程繼續執行代碼。由於這個,tt.m2()被調用。目前JVM創建了一個新線程,打印出執行runnablerunnablesysouts的恆星。可視化這種行爲。你可以添加當前時間給你system.out.print

相關問題