写2个线程,其中一个线程打印1~52,另一个线程打印A~Z,打印顺序应该是12A34B...

首先写一个Print类:

public class Print{
    private boolean flag = true;
    private int number = 0;
    public void printNumber() throws Exception{
        if(!flag){
            this.wait();//如果!flag即不是打印数字,让它等待。
        }
        for(int i = 0 ; i < 2 ; i++){//题上要求一次打印两个数字一个字母
            System.out.println(++number)
        }
        flag = false;//打印完数字就修改判断条件
        notifyAll();//唤醒其他线程
    }
    public void printLetter(int i) throws Exception{
    if(flag){
        this.wait();
    }
    System.out.println((char)('A'+i));//需要进行强制类型转换
    flag = true;
    notifyAll();

测试类:

public class MainTest(){
    Print p = new Print();
    //通过重写Runnable的run方法
    new Thread(new Runnable(){
        @Override
        public void run(){
            for(int i = 0 ; i < 26 ; i++){
                try{
                    p.printNumber();
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    new Thread(new Runnable(){
        @Override
        public void run(){
            for(int i = 0 ; i < 26 ; i++){
                try{
                    p.printLetter(i);
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

输出结果:

1
2
A
3
4
B
.....

猜你喜欢

转载自blog.csdn.net/laobanhuanghe/article/details/98946605