xxxxxxxxxx
public class MyObj {
private static volatile int a = 1;
public static void main(String[] args) {
new Thread(() -> {
int i = 1;
while (i <= 10) {
if (a == 1) {
System.out.println(i);
i += 3;
a = 2;
}
}
}).start();
new Thread(() -> {
int i = 2;
while (i <= 10) {
if (a == 2) {
System.out.println(i);
i += 3;
a = 3;
}
}
}).start();
new Thread(() -> {
int i = 3;
while (i <= 10) {
if (a == 3) {
System.out.println(i);
i += 3;
a = 1;
}
}
}).start();
}
}
xxxxxxxxxx
public class MyObj {
private static volatile int count = 1;
private static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
new Thread(() -> {
for (int i = 0; i < 10; ) {
lock.lock();
while (count % 3 == 0) {
System.out.println(count);
count++;
i++;
}
lock.unlock();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; ) {
lock.lock();
while (count % 3 == 1) {
System.out.println(count);
count++;
i++;
}
lock.unlock();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 10; ) {
lock.lock();
while (count % 3 == 2) {
System.out.println(count);
count++;
i++;
}
lock.unlock();
}
}).start();
}
}
xxxxxxxxxx
public class MyObj {
private static int count = 1;
private static ReentrantLock lock = new ReentrantLock();
private static Condition a = lock.newCondition();
private static Condition b = lock.newCondition();
private static Condition c = lock.newCondition();
public static void main(String[] args) {
new Thread(() -> {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 0) {
a.await();
}
System.out.println(count);
count++;
b.signal();
}
} catch (InterruptedException e) {
lock.unlock();
}
}).start();
new Thread(() -> {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 1) {
b.await();
}
System.out.println(count);
count++;
c.signal();
}
} catch (InterruptedException e) {
lock.unlock();
}
}).start();
new Thread(() -> {
try {
lock.lock();
for (int i = 0; i < 10; i++) {
while (count % 3 != 2) {
c.await();
}
System.out.println(count);
count++;
a.signal();
}
} catch (InterruptedException e) {
lock.unlock();
}
}).start();
}
}