题目:写两个线程 一个线程打印1-52 另一个线程打印A-Z.
打印顺序 12A34B…
public class Print{
public static void main(String[] args){
PrintSth printSth = new PrintSth();
new Thread(()->{
while(!printSth.numFlag){
printSth.printNum();
}
}).start();
new Thread(()->{
while(!printSth.letterFlag){
printSth.printLetter();
}
}).start();
}
}
//
class PrintSth extends Thread{
ReenterLock lock = new ReenterLock();
private int num = 1;
private letter = 65;
Condition condNum = lock.newCondition();
Condition condLetter = lock.newCondition();
private boolean flag = true;
public boolean numFlag = false;
public boolean letterFlag = false;
public synchonrized void printNum(){
if(num>=52){
numFlag = true;
return;
}
lock.lock();
if(flag){
condNum.await();
}
System.out.println(i);
System.out.println(i+1)
i+=2;
flag = true;
condLetter.notify();
lock.unLock();
}
public synchonrized void printLetter(){
if(num>=90){
letterFlag = true;
return;
}
lock.lock();
if(!flag){
condLetter.await();
}
System.out.println((char)(i++));
flag = false;
condNum.notify();
lock.unLock();
}
}