@JAVA多線程學習之-3個線程分别列印ABC交替5次
1. 使用Lock-Condition 實作。定義一個value 來控制哪個線程工作。因為是用if 判斷的,i++操作必須要在正确列印之後自己去控制i++,不可放在for循環力裡面
class Resource1 {
private volatile int value = 1;
private ReentrantLock lock = new ReentrantLock();
Condition condition1 = lock.newCondition();
/**
* 線程A
*/
void printA() {
try {
lock.lock();
for (int i = 0; i < 5; ) {
if (value == 1) {
System.out.print(Thread.currentThread().getName());
value = 2;
i++;
condition1.signalAll();
} else {
condition1.await();
}
}
} catch (InterruptedException e) {
} finally {
lock.unlock();
}
}
/**
* 線程B
*/
void printB() {
try {
lock.lock();
for (int i = 0; i < 5;) {
if (value == 2) {
System.out.print(Thread.currentThread().getName());
value = 3;
i++;
condition1.signalAll();
} else {
condition1.await();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 線程C
*/
void printC() {
try {
lock.lock();
for (int i = 0; i < 5; ) {
if (value == 3) {
System.out.print(Thread.currentThread().getName());
value = 1;
i++;
condition1.signalAll();
} else {
condition1.await();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
Resource1 resource1 = new Resource1();
new Thread(()->resource1.printA(),"A").start();
new Thread(()->resource1.printB(),"B").start();
new Thread(()->resource1.printC(),"C").start();
}
輸出結果:ABCABCABCABCABC
##使用 wait- notify實作,列印次數在外面控制,裡面用while判斷是哪個線程工作
class Resource3 {
private volatile int value = 1;
/**
* 線程A
*/
void printA() {
synchronized (this) {
while (value != 1) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print(Thread.currentThread().getName());
value = 2;
notifyAll();
}
}
/**
* 線程B
*/
void printB() {
synchronized (this) {
while (value != 2) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print(Thread.currentThread().getName());
value = 3;
notifyAll();
}
}
/**
* 線程C
*/
void printC() {
synchronized (this) {
while (value != 3) {
try {
wait();
} catch (Exception e) {
}
}
System.out.print(Thread.currentThread().getName());
value = 1;
notifyAll();
}
}
}
public static void main(String[] args) {
Resource3 resource1 = new Resource3();
/* new Thread(()->resource1.printA(),"A").start();
new Thread(()->resource1.printB(),"B").start();
new Thread(()->resource1.printC(),"C").start();*/
new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource1.printA();
}
}, "A").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource1.printB();
}
}, "B").start();
new Thread(() -> {
for (int i = 0; i < 5; i++) {
resource1.printC();
}
}, "C").start();
}