2016-11-18 40 views
-1

这是我的理解是使用Java同步和notify()和wait()方法,两个线程的同步是这样的:同步两个线程打印到标准错误

public class Tester { 
    public static void main(String[] args) throws InterruptedException { 
     final Business business = new Business(); 
     // 子线程 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       for (int i = 0; i < 50; i++) { 
        try { 
         business.sonBusiness(i); 
        } catch (InterruptedException e) { 
        } 
       } 
      } 
     }).start(); 
     for (int i = 0; i < 50; i++) { 
      business.mainBusiness(i); 
     } 
    } 
} 
class Business { 
    public void mainBusiness(int i) throws InterruptedException { 
     synchronized (this) { 
      for (int j = 1; j <= 20; j++) { 
       System.out.println("主线程第" + i + "轮,第" + j + "次"); 
      } 
      this.notify(); 
      this.wait(); 
     } 
    } 
    public void sonBusiness(int i) throws InterruptedException { 
     synchronized (this) { 
      for (int j = 1; j <= 30; j++) { 
       System.err.println("子线程第" + i + "轮,第" + j + "次"); 
      } 
      this.notify(); 
      this.wait(); 
     } 
    } 
} 

但是,我看到的输出(见下文)告诉我,同步不像我所期望的那样。我认为主线程和新线程可能会“一个一个”运行,并且在大多数情况下它们都会运行。但我得到以下输出。我不知道如何解释,请给我一个帮助。

enter image description here

+2

你的问题到底是什么?如果两个线程可以同时运行? – UnholySheep

+0

@UnholySheep我认为当一个线程正在打印时,另一个线程必须等待被通知。但以上输出意味着不。 – passion

+1

你可以尝试打印到主要和儿子商业的stderr。或者在打印后清除标准输出。 – Matthias

回答

3

我想这是因为你在同一时间他们打印到System.outSystem.err。在IDE中,它们可能是同一个控制台,但不能很好地同步。

+1

也许。 System.out被缓冲。而System.err不是。 – Matthias

+0

@Matthias我从来没有想过这个,但它是逻辑,因为应该马上看到错误。 :) –

+0

你的意思是2个人按预期运行,但控制台欺骗了我? – passion