迅雷笔试题
编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
Java实现代码如下:
public class PrintThread extends Thread {
private intprintCount = 0;
publicPrintThread(String threadName) {
super(threadName);
}
@Override
public voidrun() {
while(printCount <= 10) {
Print.print();
printCount++;
}
}
}
public final class Print {
private staticfinal PrintLock printLock = new PrintLock();
public staticvoid print() {
try {
printLock.lock();
System.out.print(Thread.currentThread().getName());
printLock.unlock();
} catch(InterruptedException e) {
System.out.println(e.getMessage());
}
}
}
public class PrintLock {
private charhistory = '\0';
public synchronizedvoid lock() throws InterruptedException {
charch = Thread.currentThread().getName().charAt(0);
switch(ch) {
case 'A':
while(!(history == '\0' || history == 'C')) {
wait();
}
break;
case 'B':
while(history != 'A') {
wait();
}
break;
case 'C':
while(history != 'B') {
wait();
}
break;
}
}
public synchronizedvoid unlock() {
history= Thread.currentThread().getName().charAt(0);
notifyAll();
}
}
public class Main {
public staticvoid main(String[] args) {
PrintThreada = new PrintThread("A");
PrintThreadb = new PrintThread("B");
PrintThreadc = new PrintThread("C");
a.start();
b.start();
c.start();
}
}