2016-02-26 39 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

相关问题