这个是昨日面试时的一个题目,考查的是线程同步与协调处理相关的知识。但当时的我是在线写的,但后来发现完全错了。之前自我感觉对多线程已经掌握的很OK了,结果当时全懵了。哈哈,只是当时已惘然。
现在参考这篇文章:https://yq.aliyun.com/articles/34834
自己再写个类似的,以加深认识吧。
public class PrintABC {
public static void main(String[] args) {
Print print = new Print();
Thread thread_a = new Thread(new PrintThread(print, 'A'));
Thread thread_b = new Thread(new PrintThread(print, 'B'));
Thread thread_c = new Thread(new PrintThread(print, 'C'));
thread_a.start();
thread_b.start();
thread_c.start();
}
}
class PrintThread implements Runnable {
//打印机只有一台
private Print print;
//设置默认值[即第一个打印值]和下一个的打印值
private static volatile char next='A';
private char val;
public PrintThread(Print print, char val) {
this.print = print;
this.val = val;
}
public void run() {
try {
for (int i = 0; i < 10; ) {
synchronized (print) {
//协调线程顺序打印ABCABC
if(val=='A'&&next==val) {
print.print(val);
next='B';
i++;
}
if(val=='B'&&next==val) {
print.print(val);
next='C';
i++;
}
if(val=='C'&&next==val) {
print.print(val);
next='A';
i++;
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
class Print {
//private char next;
public void print(char val) throws Exception {
System.out.print(val);
}
}
结果为:ABCABCABCABCABCABCABCABCABCABC