【发布时间】:2020-01-26 05:01:29
【问题描述】:
我已经设置了标志的值,但结果不是'add'和'sub'交替出现。为什么?当我查看结果时,它执行了两次“sub”方法。但是当 'sub' 方法结束时,标志的值将被设置为 'false'。但是结果却连续打印了两次“subxxxxxx”。
class Resource {
private boolean flag = true;
private int num = 0;
// At here I have declared an add()
public synchronized void add() throws InterruptedException {
if (this.flag == false) {
super.wait();
}
Thread.sleep(100);
this.num++;
System.out.println("addition:"+Thread.currentThread().getName() + this.num);
this.flag = false;
super.notifyAll();
}
// At here I have declared an sub()
public synchronized void sub() throws InterruptedException {
if (this.flag == true) {
super.wait();
}
Thread.sleep(200);
this.num--;
System.out.println("subtraction:"+Thread.currentThread().getName() + this.num);
this.flag = true;
super.notifyAll();
}
}
/*
* I will test it with multiple threads. For example:
*new Thread(ad, "add").start();
*new Thread(ad, "add").start();
*new Thread(sub, "sub").start();
*new Thread(sub, "sub").start();
*When threads start. it will execute alternately. For example:
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
Thread add:0
Thread sub:-1
But the result is like this:
Thread add:0
Thread sub:-1
Thread sub:-2
Thread add:-1
Thread sub:-3
Thread sub:-4
Why?Why?Why?
*/
new Thread(ad, "add").start();
new Thread(ad, "add").start();
new Thread(sub, "sub").start();
new Thread(sub, "sub").start();
}
}
【问题讨论】:
-
我想不通。请帮帮我-0-
-
此代码不会按原样编译。请编辑并确保它可以编译。
-
如果没有看到所有代码,我们无法解释这是做什么的。
-
代码太长。他不允许我全部上传
-
我使用了多个线程。但结果不是交替调用add()和sub()。
标签: java multithreading synchronized