我有一些关于两个线程同步的问题。
这是主要的:
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
.
.
最佳答案
您的count
是一个实例变量,同步机制也是如此。如果您想在不同实例之间共享它们,它们需要是静态
:
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;
}
}}
关于java - 线程不同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56302651/