qq_38969881 2019-09-29 22:36 采纳率: 0%
浏览 216

萌新问一个java多线程同步死锁的问题

下面这两段代码,一个实现Runnable接口,一个继承Thread类,前面的能正常交替输出
但是后面继承Thread的运行会死锁,没想明白为什么会死锁,求指教

public class Test3 {
       static  class MyRun implements Runnable {
            static int i = 0;
            @Override
            public synchronized  void run() {
                for (int j = 0; j < 10; j++) {
                    if(i%2==0)
                        System.out.println(Thread.currentThread().getName()+":A");
                    else
                        System.out.println(Thread.currentThread().getName()+":B");
                    i++;
                    this.notifyAll();
                    try {
                        if(i>=19)
                            Thread.sleep(10);
                        else
                            this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) {
            MyRun myRun = new MyRun();
            Thread a = new Thread(myRun);
            Thread b = new Thread(myRun);
            a.start();
            b.start();
        }
    }
public class Test3 {
       static  class MyRun extends Thread {
            static int i = 0;
            @Override
            public synchronized  void run() {
                for (int j = 0; j < 10; j++) {
                    if(i%2==0)
                        System.out.println(Thread.currentThread().getName()+":A");
                    else
                        System.out.println(Thread.currentThread().getName()+":B");
                    i++;
                    this.notifyAll();
                    try {
                        if(i>=19)
                            Thread.sleep(10);
                        else
                            this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        public static void main(String[] args) {
            MyRun m1 = new MyRun();
            MyRun m2 = new MyRun();
            m1.start();
            m2.start();
        }
    }
  • 写回答

4条回答 默认 最新

  • Json-Huang 2019-09-30 09:32
    关注

    int i = 0;移到run方法中试试,去掉static

    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?