如何调试多线程java程序

时间:2014-06-03 12:54:01

标签: java eclipse multithreading

我有程序,我在其中设置了一些调试点,但是当控制到达wait方法旁边的printEven方法时,控制转到等待方法并变为隐藏且没有任何反应。任何人都可以解释如何调试等待。控制进入等待方法,永远不会返回。我正在使用eclipse进行调试。

public class PrintEvenOddTester 
    {
        public static void main(String ... args)
        {
            Printer print = new Printer();
            Thread t1 = new Thread(new TaskEvenOdd(print, 10,  false));
            Thread t2 = new Thread(new TaskEvenOdd(print, 10, true));
            t1.start();
            t2.start();
        }
    }
    class TaskEvenOdd implements Runnable 
    {
        private int max;
        private Printer print;
        private boolean isEvenNumber;
        TaskEvenOdd(Printer print, int max, boolean isEvenNumber)
        {
            this.print = print;
            this.max = max;
            this.isEvenNumber = isEvenNumber;
        }
        public void run() 
        {
            //System.out.println("Run method");
            int number = isEvenNumber == true ? 2 : 1;
            while(number<= max)
            {
                if(isEvenNumber)
                {
                    //System.out.println("Even :"+ Thread.currentThread().getName());
                    print.printEven(number);
                    // number+=2;
                }   
                else 
                {
                    //System.out.println("Odd :"+ Thread.currentThread().getName());
                    print.printOdd(number);
                  // number+=2;
                }
                number+=2;
            }
        }
    }

    class Printer 
    {
        boolean isOdd= false;
        synchronized void printEven(int number) 
        {
            while(isOdd == false)
            {
                try 
                {
                    wait();
                } catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
            System.out.println("Even:"+number);
            isOdd = false;
            notifyAll();
        }
        synchronized void printOdd(int number) 
        {
            while(isOdd == true)
            {
                try 
                {
                    wait();
                } catch (InterruptedException e) 
                {
                    e.printStackTrace();
                }
            }
            System.out.println("Odd:"+number);
            isOdd = true;
            notifyAll();
        }
    }

0 个答案:

没有答案