有人可以解释为什么程序没有结束?

时间:2017-10-28 11:50:30

标签: java multithreading concurrency wait notify

  

嗨,我是java线程的新手。我正在试图弄清楚是什么   wait()和notify()methods.So我写了简单的程序,但我不能   找到无限执行的原因。请问有人可以帮我解决这个问题吗?

public class StairCase {
    public static void main(String[] args) {
        int[] lst = {1,2,3,4,5,6,7};
        Test1 t1 = new Test1(lst);
        t1.setName("Test 1 ");
        Test2 t2 = new Test2(lst);
        t2.setName("Test 2 ");
        t1.start();
        t2.start();
    }
}

class Test1 extends Thread {
    int[] line ;
    public Test1(int[] lst) {
        this.line = lst;
    }
    public void run(){
        synchronized(line) {
            for (int i = 0; i < 5; i++) {
                try{
                    if(i == 2) line.wait();
               } catch (Exception e) {

               }
               System.out.println(Thread.currentThread().getName() + line[i]);
            }
        }
    }

}

class Test2 extends Thread {
    int[] line ;
    public Test2(int[] lst) {
        this.line = lst;
    }
    public void run() {
        synchronized(line) {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + line[i]);
            }
        }
        try {
            line.notify();
        } catch(Exception e) {
        }
    }
}

1 个答案:

答案 0 :(得分:0)

public class StairCase {
    public static void main(String[] args) {
        int[] lst = {1,2,3,4,5,6,7};
        Test1 t1 = new Test1(lst);
        t1.setName("Test 1 ");
        Test2 t2 = new Test2(lst);
        t2.setName("Test 2 ");
        t1.start();
        t2.start();
    }
}

class Test1 extends Thread {
    private final int[] line ;
    Test1(int[] lst) {
        this.line = lst;
    }
    public void run(){
        synchronized(line) {
            for (int i = 0; i < 5; i++) {
                try{
                    if(i == 2) line.wait();
                } catch (Exception e) {
                  e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + line[i]);
            }
        }
    }

}

class Test2 extends Thread {
    private final int[] line ;
    Test2(int[] lst) {
        this.line = lst;
    }
    public void run() {
        synchronized(line) {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + line[i]);
            }
        }
        try {
            synchronized (line) {
                line.notify();
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

试试这段代码是你预期的结果吗?如果没有让我知道期望结果是什么。

我添加了e.printStackTrace();对于catch块和已检查天气,如果有异常,并且有一个例外,例外是在notify()的第45行,所以我用synchronized语句包围了通知。

        synchronized (line) {
            line.notify();
        }