寫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
.....
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章