当前位置: 代码迷 >> 综合 >> Java Object wait notify 机制实现两个线程交替打印问题
  详细解决方案

Java Object wait notify 机制实现两个线程交替打印问题

热度:4   发布时间:2024-01-14 04:36:15.0

线程1负责打印a,b,c,d

线程2负责打印1,2,3,4

要求控制台中输出的内容为 a1b2c3d4

package com.sdmjhca.springBootDemo.countdownlatch;


/**  * @author JHMI on 2017/8/28.  */ public class TestMain {static final Object object = new Object();
    public static void main(String[] args) throws InterruptedException {new Thread(new Runnable() {String a[] = {
  "a","b","c","d"};
            @Override
            public void run() {for(int i=0;i< 4 ;i++){synchronized (object){System.out.println("线程a 开始执行");
                        object.notify();
                        try {System.out.println("线程a 开始等待");
                            object.wait();
                        } catch (InterruptedException e) {e.printStackTrace();
                        }System.out.println("线程a 继续执行");
                        System.out.println(a[i]);
                        System.out.println("线程a 执行结束");
                        object.notify();
                    }}}}).start();
        new Thread(new Runnable() {int a[] = {
  1,2,3,4};
            @Override
            public void run() {for(int i=0;i<4;i++){synchronized (object){System.out.println("线程1 开始执行");
                        object.notify();
                        try {System.out.println("线程1 开始等待");
                            object.wait();
                        } catch (InterruptedException e) {e.printStackTrace();
                        }System.out.println("线程1  继续执行");
                        System.out.println(a[i]);
                        System.out.println("线程1  执行结束");
                    }}}}).start();
    }
}