Sie Lock-Variablen verwenden „a“ und "b" und synchronisieren sie zum Sperren des "kritischen Abschnitts" in umgekehrter Reihenfolge. Z.B. Benachrichtige "a", dann "b", "DRUCKEN", Benachrichtige "b" und dann "a".
Siehe die unter dem Code: -
public class EvenOdd {
static int a = 0;
public static void main(String[] args) {
EvenOdd eo = new EvenOdd();
A aobj = eo.new A();
B bobj = eo.new B();
aobj.a = Lock.lock1;
aobj.b = Lock.lock2;
bobj.a = Lock.lock2;
bobj.b = Lock.lock1;
Thread t1 = new Thread(aobj);
Thread t2 = new Thread(bobj);
t1.start();
t2.start();
}
static class Lock {
final static Object lock1 = new Object();
final static Object lock2 = new Object();
}
class A implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
System.out.println(++EvenOdd.a + " A ");
synchronized (a) {
a.notify();
}
synchronized (b) {
b.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class B implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
synchronized (b) {
b.wait();
System.out.println(++EvenOdd.a + " B ");
}
synchronized (a) {
a.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
OUTPUT: - 1 A 2 B 3 A 4 B 5 A 6 B 7 A 8 B 9 A 10 B
Vielen Dank für die Antwort, aber wie würdest du? beziehen Sie sich beispielsweise auf "Flagge" von innen T1? Ich habe etwas wie ParentClass.flag versucht (wo ParentClass die Klasse ist, von der ich "main" und "help" starte) und es scheint nicht zu funktionieren ... – user1031431
Instanziiere T1/T2 mit einem Verweis auf ihre enthaltende Klasse , und mache die Flagge ein Mitglied dieser Klasse? –