Java实现两个线程交替打印的功能

  • Post author:
  • Post category:java



要求:

线程1负责打印a、b、c、d,线程2负责打印1、2、3、4,要求输出的内容为:a1b2c3d4。


代码实现如下:

public class TestDemo {
    static final Object object = new Object();
    static private boolean flag = false;
    public static void main(String[] args) throws InterruptedException {
        new Thread(new Runnable() {
            String[] arr = {"a","b","c","d"};
            @Override
            public void run() {
                for(int i=0; i<4 ;i++){
                    synchronized (object){
                        if(flag){
                            try {
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.print(arr[i]+ " ");
                        flag = true;
                        object.notify();
                    }
                }
            }
        }).start();
        new Thread(new Runnable() {
            int[] arr = {1,2,3,4};
            @Override
            public void run() {
                for(int i=0; i<4; i++){
                    synchronized (object){
                        if(!flag){
                            try {
                                object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        System.out.print(arr[i]+ " ");
                        flag = false;
                        object.notify();
                    }
                }

            }
        }).start();
    }
}


输出结果如下:


在这里插入图片描述



版权声明:本文为zxy5663原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。