听说有这样的面试题: 关于多线程的, 使用两个线程, 交替打印26个字母: 如下所示 线程1: 输出A 线程2: 输出B 线程1: 输出C 线程2: 输出D … 今天先用最初级的互斥锁实现一下, 时间问题, 后面文章还有其它方式, 思路看代码
public class T09_PrintAB {
private volatile static int index = 0;
private static String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public synchronized static void printChars() {
while (index < 26) {
char c = chars.charAt(index);
System.out.println("Thread_name: " + Thread.currentThread().getName() + " " + c);
try {
index++;
T09_PrintAB.class.notify();
if (index >= 24)
break;
T09_PrintAB.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Thread(() -> {
printChars();
}, "Thread_01").start();
new Thread(() -> {
printChars();
}, "Thread_02").start();
}
}
Love Coding. Mark
|