DreamCats/java-notes

多线程练习题的第二题问题

Opened this issue · 0 comments

感谢同学分享这么好的资源。多线程练习题的第二题是存在一定问题的(每个线程把自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示),已有的代码如果建立在start之后按照threadA threadB和threadC的顺序执行是没错的,但是实际上线程调度的顺序并不是start的顺序,所以会出现问题,经过测试也确实结果不符合题目要求,附上自己的思路。

public class Test2 {
    
    //记录打印状态
    private static int status = 0;
    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                int id = Integer.valueOf(Thread.currentThread().getName());
                //锁住
                synchronized (this){
                    try {
                        for (int i = 0; i < 10; i++) {
                            //判断
                            while (status != id){
                                wait();
                            }
                            //干活
                            System.out.print((char)(id+'A'));
                            status = (status+1)%3;
                            //通知
                            notifyAll();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        new Thread(r, "0").start();
        new Thread(r, "1").start();
        new Thread(r, "2").start();
    }
}