エンド ユーザー クラス (ClassA & ClassB) で同期する代わりに、motorA クラス自体で同期できます。そのアクションを同期させるのは、MotorA クラスの責任です。
MotorA クラス :
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();
}
}