Java实现两个线程交替打印问题

线程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();
    }
}

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