我对两个线程的同步有一些问题。
这是主要内容:
public class Main {
public static void main(String[] args) throws InterruptedException {
new Thread(new TaskA()).start();
//Thread.currentThread().sleep(3000);
new Thread(new TaskB()).start();
}
}
这是我的两个增加/减少共享变量“ count”的线程
public class TaskA extends Manager implements Runnable {
@Override
public void run() {
while(true){
try {
decrement();
System.out.println("Thread A: " + getCount());
Thread.sleep((long) Math.random()%4000);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
public class TaskB extends Manager implements Runnable {
@Override
public void run() {
while(true){
try {
increment();
System.out.println("Thread B: " + getCount());
Thread.sleep((long) Math.random()%4000);
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
操作由此类管理:
public class Manager {
private int count=0;
public synchronized void increment() throws InterruptedException {
if(count>=0){
count++;
}else {
wait();
notifyAll();
}
}
public synchronized void decrement()throws InterruptedException {
//wait();
if(count <10){
count--;
}else {
wait();
notifyAll();
}
}
public synchronized int getCount(){
return count;
}}
这是我期望的输出:
-ThreadA: 1
-ThreadA: 2
-ThreadA: 3
.
.
-ThreadB: 10
-ThreadB: 9
-ThreadB: 8
.
.
-ThreadA: 1
-ThreadA: 2
-ThreadA: 3
.
.
答案 0 :(得分:1)
您的count
是实例变量,同步机制也是如此。如果要在不同的实例之间共享它们,则它们必须为static
:
public class Manager {
// Made static so that all managers share the same count
private static int count = 0;
public void increment() throws InterruptedException {
// Synchronizing on a resource shared between all instances:
synchronized (Manager.class) {
if (count >= 0) {
count++;
} else {
wait();
notifyAll();
}
}
}
public void decrement() throws InterruptedException {
// Synchronizing on a resource shared between all instances:
synchronized (Manager.class) {
//wait();
if (count < 10) {
count--;
} else {
wait();
notifyAll();
}
}
}
public int getCount() {
// Synchronizing on a resource shared between all instances:
synchronized (Manager.class) {
return count;
}
}}