[英]How to use wait() and notify() for counter in java?
I have two threads that increment a counter and I want that they do it in an alternating manner, meaning that first thread one accesses the counter object, then thread two, thread one again... I was told that this can be achieved with wait()
and notify()
but I can't figure out how to use them properly.我有两个线程增加一个计数器,我希望它们以交替的方式进行,这意味着第一个线程访问计数器 object,然后线程二,线程一再次......我被告知这可以通过
wait()
来实现wait()
和notify()
但我不知道如何正确使用它们。
class counter {
int val;
public counter() {
val = 0;
}
public incr() {
val++;
}
}
One solution could look like that:一种解决方案可能如下所示:
public class ThreadA implements Runnable {
counter count;
int activeThreads;
int id;
int iterations;
public Thread A(int activeThreads, int id, counter count, int iterations) {
this.activeThreads = activeThreads;
this.id = id;
this.count = count;
this.iterations = iterations;
}
@Override
public void run() {
for (int i = 0; i < iterations; i++) {
synchronized (count) {
/* achieving alternating manner by working in the
corresponding modulo ring, assuming that the id's
are chosen accordingly (0, 1, 2, 3, ...)
*/
while (counter.value() % activeThreads != id) {
try {
counter.wait();
} catch (InterruptedException e) {
System.out.printf("Thread with id %d got
interrupted\n", id);
}
}
counter.increment();
counter.notifyAll();
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.