下面这两段代码,一个实现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();
}
}