写两个线程,一个线程打印1-52,另一个线程打印A-Z,打印顺序是12A34B…5152Z
解题思路:
根据打印顺序我们可以看到是两个数字+一个大写字母为一个循环;明确循环后要保证两个线程是交替进行(且打印数字在前),故需要设置标志位明确保证此时要运行哪个线程;之后再创建线程即可。
class Print{
//标记位
private boolean flag=true;
private Integer count=1;
//打印数字
public synchronized void printNumber(){
if(flag==false){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(2*count-1);
System.out.print(2*count);
flag=false;
notify();
}
//打印字母
public synchronized void printChar(){
if(flag==true){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print((char)('A'+count-1));
flag=true;
//两个数字一个字母为依次循环
count++;
notify();
}
}
public class Test{
public static void main(String[] args) {
Print print=new Print();
new Thread(()->{
for(int i=0;i<26;i++){
print.printNumber();
}
}).start();
for(int i=0;i<26;i++){
Thread thread=new Thread();
print.printChar();
thread.start();
}
}
}