@Yano
2017-07-31T20:54:32.000000Z
字数 1769
阅读 3337
面试题
3个线程A,B,C分别打印三个字母,每个线程循环10次,首先同步,如果不满足打印条件,则调用wait()函数一直等待;之后打印字母,更新state,调用notifyAll(),进入下一次循环。
public class printABC {
private static int state = 0;
public static void main(String[] args) {
final printABC t = new printABC();
Thread A = new Thread(new Runnable() {
public void run() {
// 设定打印10次
for (int i = 0; i < 10; i++) {
synchronized (t) {
// 如果不满足A的打印条件,则调用wait,一直阻塞
while (state % 3 != 0) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 执行到这里,表明满足条件,打印A,设置state
// 调用notifyAll方法
System.out.print("A");
state++;
t.notifyAll();
}
}
}
});
Thread B = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (t) {
while (state % 3 != 1) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print("B");
state++;
t.notifyAll();
}
}
}
});
Thread C = new Thread(new Runnable() {
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (t) {
while (state % 3 != 2) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("C");
state++;
t.notifyAll();
}
}
}
});
A.start();
B.start();
C.start();
}
}
最近看到了原来写的博客,觉得当时写得并不是很好,重新写了一下,记录之。
package test;
public class PrintABC {
private static final int PRINT_A = 0;
private static final int PRINT_B = 1;
private static final int PRINT_C = 2;
private static class MyThread extends Thread {
int which; // 0:打印A;1:打印B;2:打印C
static volatile int state; // 线程共有,判断所有的打印状态
static final Object t = new Object();
public MyThread(int which) {
this.which = which;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (t) {
while (state % 3 != which) {
try {
t.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(toABC(which)); // 执行到这里,表明满足条件,打印
state++;
t.notifyAll(); // 调用notifyAll方法
}
}
}
}
public static void main(String[] args) {
new MyThread(PRINT_A).start();
new MyThread(PRINT_B).start();
new MyThread(PRINT_C).start();
}
private static char toABC(int which) {
return (char) ('A' + which);
}
}