java - 初始化时死锁

标签 java multithreading

为什么这会在启动时立即陷入死锁 - 它打印一行然后卡住(在建议的编辑之后)?
这可能是因为第一个线程在开始等待之前错过了通知触发器。
分辨率是多少?

public class threadTwo{
    AtomicInteger i=new AtomicInteger(0);
    Boolean b=new Boolean(false);

    class firstThread implements Runnable{
        AtomicInteger i;
        Boolean b;
        firstThread(AtomicInteger i,Boolean b){
            this.i=i;
            this.b=b;
        }
        public void run(){
            while(true){
                synchronized(i){
                    try{
                        while(b==false)
                            i.wait();

                        if(i.intValue()<30){
                            i.incrementAndGet();
                            System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
                        }
                        b=false;
                        i.notify();

                    }catch(InterruptedException x){}
                }
            }
        }       
    }

    class secondThread implements Runnable{
        AtomicInteger i;
        Boolean b;
        secondThread(AtomicInteger i,Boolean b){
            this.i=i;
            this.b=b;
        }
        public void run(){
            while(true){
                synchronized(i){
                    try{
                        while(b==true)
                                i.wait();

                        if(i.intValue()<40){
                            i.getAndAdd(2);
                            System.out.println( Thread.currentThread().getId() + " - " + i.intValue());
                        }
                        b=true;
                        i.notify();

                    }catch(InterruptedException x){}
                }
            }
        }       
    }

    void runThread(){ 
        Thread t1 = new Thread(new firstThread(i,b));
        Thread t2 = new Thread(new secondThread(i,b));
        t1.start();
        t2.start();
        try{
            t1.join();
            t2.join();
        }catch(Exception e){}
        System.out.println("Result : " + i.intValue());
    }

    public static void main(String[] args){
        new threadTwo().runThread();

    }

}

最佳答案

问题出在 firstThread 中的 b.wait()。 这个变量 b 永远不会从 secondThread 得到通知,因为 secondThread 在检查 if(b==true) 时失败。 code> 并立即返回。

但也要注意这样一个事实,通过变量 b 进行同步非常糟糕,因为语句 b=false;b=true; 正在将新实例分配给变量,因此 firstThreadsecondThread 失去连接。

关于java - 初始化时死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43952068/

相关文章:

java - 使用 Java 从 IBM i 获取 DB2 数据

java - 在 Eclipse 中确定 Java 项目依赖关系

java - 保存 EditText 并自动检索

c# - .Net 4.0 中的并行功能

java - 线程转储分析器

java - 我如何知道上下文是 Activity 还是 IntentService?

Java多线程: All of my threads get the same thread id

java - 线程中出现异常 "main"java.lang.OutOfMemoryError : Java heap space on eclipse

java ExecutorService 如何处理超时

java - 如何反转该位操作数?