两个线程轮流输出唤醒题目分析

Q:两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D……

分析:

    首先是创建两个线程

    一个逻辑写输出数字,并且每两个都要wait,等待字母的输出

    一个逻辑写输出字母,并且每次先调用sleep休眠等待数字的输出,然后一次打印一个并唤醒数字线程

代码实现:

package com.qin;

/**
 * Created by SunYuqin in 2018/8/9
 * Description:
 * 创建两个线程,其中一个输出1-52,另外一个输出A-Z。输出格式要求:12A 34B 56C 78D……
 **/

public class Test04 {
    public static void main(String[] args) {
        Object obj = new Object();
        new Thread() {
            @Override
            public void run() {

                synchronized (obj) {
                    for (int i = 1; i <= 52; i++) {
                        if (i % 2 == 0) {
                            System.out.print(i);
                            try {
                                obj.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        } else {
                            System.out.print(i);

                        }
                    }
                }
            }


        }.start();

        new Thread() {
            @Override
            public void run() {
                int i = 65;
                while (i < 91) {
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    synchronized (obj) {
                        System.out.println((char) i++);
                        obj.notify();
                    }
                }
            }

        }.start();


    }
}

猜你喜欢

转载自blog.csdn.net/qq_35472880/article/details/81531455