线程练手 三个线程依次调用 顺序输出 A B C
写完代码一直在报 IllegalMonitorStateException,current thread is not owner ,我已经加了obj.notify(); 后来我又换成了obj.notifyALl();也还是在报错,后来发现 我放在synchronized锁外了,
synchronized (obj) {
System.out.println("BB");
try {
obj.wait();
obj.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
报错解决之后又有了新的问题, 开了三个线程,循环了100次调用,但是只输出了A就停止了 ,DeBug了一下,按下一个方法直接跳出去了? 跳没了? 我就莫名其妙,后来我发现了
下面是错误的代码
原因我目前只能解释为: run是线程的一个方法 start才是开始线程
public static void main(String[] args) {
Object obj = new Object();
T1 t1 = new T1(obj);
T2 t2 = new T2(obj);
T3 t3 = new T3(obj);
for (int i = 0; i < 100; i++) {
t1.run()
t2.run()
t3.run()
}
}
直接贴完整代码吧!
class Num {
static int num = 0;
public void count(int num) {
this.num = num;
}
}
class T1 implements Runnable {
private Object obj;
public T1(Object obj) {
this.obj = obj;
}
@Override
public void run() {
if (Num.num == 0) {
Num.num = 1;
synchronized (obj) {
System.out.println("A");
try {
obj.wait();
obj.notifyAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class T2 implements Runnable {
private Object obj;
public T2(Object obj) {
this.obj = obj;
}
@Override
public void run() {
if (Num.num == 1) {
Num.num = 2;
synchronized (obj) {
System.out.println("B");
try {
obj.wait();
obj.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
class T3 implements Runnable {
private Object obj;
public T3(Object obj) {
this.obj = obj;
}
@Override
public void run() {
if (Num.num == 2) {
Num.num = 0;
synchronized (obj) {
System.out.println("C");
try {
obj.wait();
obj.notify();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class demo01 {
public static void main(String[] args) {
Object obj = new Object();
T1 t1 = new T1(obj);
T2 t2 = new T2(obj);
T3 t3 = new T3(obj);
for (int i = 0; i < 100; i++) {
new Thread(t1).start();
new Thread(t2).start();
new Thread(t3).start();
}
}
}
更新一版
if会存在虚假唤醒 换成while循环就可以解决