每日一问 - 三个线程交替打印 ABCABC…
问题
三个线程交替打印 ABCABC.. ?
三个线程交替打印 ABCABC.. 10 次?
解决方案
三个线程交替打印 ABCABC…
创建共享资源 :
/**
* wait notify 实现 ABC交替打印
*/
public class ABCCoreHolder {
private int counter = 0;
public void printA() throws InterruptedException {
synchronized (this) {
//不用if, 防止操作系统虚度唤醒
while (counter % 3 != 0) {
wait();
}
System.out.print("A");
counter++;
TimeUnit.MILLISECONDS.sleep(500);
//三个以上线程一定要用 notifyAll
notifyAll();
}
}
public void printB() throws InterruptedException {
synchronized (this) {
while (counter % 3 != 1) {
wait();
}
System.out.print("B");
counter++;
TimeUnit.MILLISECONDS.sleep(500);
//三个以上线程一定要用 notifyAll
notifyAll();
}
}
public void printC() throws InterruptedException {
synchronized (this) {
while (counter % 3 != 2) {
wait();
}
System.out.print("C");
counter++;
TimeUnit.MILLISECONDS.sleep(500);
//三个以上线程一定要用 notifyAll
notifyAll();
}
}
}
测试用例
public static void abcLoopTest() {
final ABCCoreHolder holder = new ABCCoreHolder();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
holder.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
holder.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
holder.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
结果:
ABCABCABCABCABCABCABC...
三个线程交替打印 ABCABC… 10 次
public static void abcLoop10Test() {
final ABCCoreHolder holder = new ABCCoreHolder();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
holder.printA();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
holder.printB();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
try {
holder.printC();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
结果:
ABCABCABCABCABCABCABCABCABCABC
Process finished with exit code 0