无需在最终用户类(ClassA 和 ClassB)上进行同步,您可以在您的 motorA 类本身中进行同步。同步其动作应该是 MotorA 类的责任。
电机A类:
public class MotorA {
private static MotorA instance = new MotorA();
private static int pointer = 0;
private MotorA() {
}
public static MotorA getInstance() {
return instance;
}
public void rotate() {
synchronized(MotorA.class) {
System.out.println(Thread.currentThread() + " Rotating "+ pointer++);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
MotorA 类的最终用户 - ClassA 和 ClassB 对其他线程的存在不太了解。
public class ClassA implements Runnable {
@Override
public void run() {
doRotate();
}
private void doRotate() {
MotorA motor = MotorA.getInstance();
while (true) {
motor.rotate();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class ClassB implements Runnable {
@Override
public void run() {
doRotate();
}
private void doRotate() {
MotorA motor = MotorA.getInstance();
while (true) {
motor.rotate();
try {
Thread.sleep(15);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
这里是主程序。
public class Main {
public static void main(String[] args) {
Thread a = new Thread(new ClassA());
Thread b = new Thread(new ClassB());
Thread c = new Thread(new ClassA());
Thread d = new Thread(new ClassB());
a.start();
b.start();
c.start();
d.start();
}
}