java多线程编程(打印12A34B...5152Z)

1.题目描述

写两个线程,一个线程打印1-52,一个线程打印A-Z,打印顺序为12A34B56C...5152Z.

2.解题思路

2.1先写打印数字的方法

//    设置标记位,如果flag为true,打印两个数字;如果flag为false,打印一个字母
    private boolean flag = true;
//    创建一个变量count用来往后打印
    private int count = 1;
//    打印数字方法(因为要顺序打印所以用到锁)
    public synchronized void printNum(){
//    如果flag为false,等待
        if(flag == false){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//    flag为true,打印两个数字
        System.out.print(2*count -1);
        System.out.print(2*count);
//    该打印字母
        flag = false;
        notify();
    }

2.2写打印字母的方法

    public synchronized void printChar(){
        if(flag==true){
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
//    利用count来实现字符的往后打印
        System.out.print((char)('A'+count-1));
//    打印下一波数字
        flag = true;
//    数字字母打印完后利用count值往后打印
        count++;
        notify();
    }

3.整体代码如下

class Print{
    private boolean flag = true;
    private int count = 1;
//    打印数字方法
    public synchronized void printNum(){
        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();
//        打印数字线程(因为总共需要打印26次)
        new Thread(()->{
            for(int i=0;i<26;i++){
                print.printNum();
            }
        }).start();
//        打印字母线程
        new Thread(()->{
            for(int i=0;i<26;i++){
                print.printChar();
            }
        }).start();
    }
}

4.运行结果

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(java语言)