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

    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料