2016-04-06 46 views
1

我有两个线程同时运行,一个主线程和一个旧的布尔变量类,我目前有一个thrad打印赔率和其他打印evens,但我让他们等待彼此以便它按顺序打印1 - 100。在java中的类同步

我目前在我的NumberPrinter类中引用了一个布尔对象,并且我正在使用它来使线程进入等待状态以等待另一个对象。我知道如何在同一个类中进行同步,但是当我尝试在线程间进行同步时,它会挂起并看起来像布尔变量没有被更新或与两个线程同步。至少,这就是为什么我认为是问题

感谢任何建议表示赞赏

我的测试类

public class Test { 

    public static void main(String[] args) throws InterruptedException { 

     NumberPrinter np = new NumberPrinter(); 
     single ent = new single(np);// new state 
     Double ont = new Double(np);// new state 


     ent.start(); 
     ont.start(); 


    } 

} 

类甚至

public class single extends Thread { 

    private NumberPrinter printer; 

    public single(NumberPrinter np) { 
     this.printer = np; 
    } 

    public synchronized void run() { 
     try { 

      for (int i = 1; i <= 100; i++) { 
       System.out.println(printer.isOdd); 
       if (i % 2 == 0) { 
        if (printer.isOdd == true) { 
         wait(); 
        } 
        System.out.println(i); 
        printer.isOdd = true; 
        notifyAll(); 
       } 
      } 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 

类奇

public class Double extends Thread { 

    private NumberPrinter printer; 
    public Double(NumberPrinter np) { 
     this.printer = np; 
    } 


    public synchronized void run() { 
     try { 
      for (int i = 1; i <= 100; i++) { 
       System.out.println(printer.isOdd); 
       if (i % 2 == 1) { 
        if (printer.isOdd == false) { 
         wait(); 
        } 
        System.out.println(getName() + ": " + i); 
        printer.isOdd = false; 
        notifyAll(); 
       } 
      } 
     } catch (InterruptedException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

} 

一个类来保存布尔变量

package single; 

public class NumberPrinter { 

    public boolean isOdd = true; 

} 

回答

0

waitnotifyAll需要被调用从两个线程对同一对象。您还需要同步该对象。你正在使用线程实例,但有两个不同的实例。你可以使用printer这个对象,或者你可以创建一个new Object()并使用它。 wait也应在while循环中使用,而不是在if语句中使用。

public void run() { 
    try { 
     for (int i = 1; i <= 100; i++) { 
      synchronized(printer) { 
       System.out.println(printer.isOdd); 
       if (i % 2 == 1) { 
        while (printer.isOdd == false) { 
         printer.wait(); 
        } 
        System.out.println(getName() + ": " + i); 
        printer.isOdd = false; 
        printer.notifyAll(); 
       } 
      } 
     } 
    } catch (InterruptedException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 
+0

感谢这个修好了!我非常感谢帮助 –