两个线程实现打印100次AB字符串——腾讯面试

public class Test {
    private boolean flag = true;
    public static void main(String[] args) {
        Test vt = new Test();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    vt.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    vt.printB();
                }
            }
        }).start();
    }

    private synchronized void printA(){
        while (!flag){
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.print("A");
        flag = false;
        notify();
    }
    private synchronized void printB(){
        while (flag){
            try{
                wait();
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
        System.out.print("B");
        flag = true;
        notify();
    }
}

效果是ABABABAB...

三个线程打印ABC

public class Main4 {
    char chars = a;

    public static void main(String[] args){
        Main4 m = new Main4();

        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0 ;  i <100 ; i++){
                 m.printA();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0 ;  i <100 ; i++){
                    m.printB();
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int i = 0 ;  i <100 ; i++){
                    m.printC();
                }
            }
        }).start();
    }
    public synchronized boolean getNum( char c) {
        if(chars==c) {
            if (chars == a || chars==b) {
                chars++;
            } else {
                chars=a;
            }
            System.out.println(c);
            return true;
        }
        return false;
    }

    public  void printA(){
            while(!getNum( a)) {

            }
    }
    public  void printB(){

            while(!getNum( b)) {

            }
    }
    public void printC(){

            while (!getNum(c)){
            }
    }
}
经验分享 程序员 微信小程序 职场和发展