用多线程完成一个小题目(多线程通信)

看到一个简单的题目,就是用两个线程,输出1a2b3c4d5e ...

首先,两个线程去跑其中一个数据,顺序是随机的,不可能这么一次交替生成,故需要线程直接通信,告诉对方,你跑完了就该我了,

确定之后,就想到了最基础的,synchronized,notify和wait来实现,话不多说,上代码

 

 

public class CommunicationB {

    static char[] num = {'1', '2', '3', '4', '5', '6'};
    static char[] chars = {'a', 'b', 'c', 'd', 'e'};

    Object shareObject = new Object();
    Boolean first = true;


    public void run() {
        new ThreadOne().start();
        new ThreadTwo().start();
    }

    public static void main(String[] args) {
        new CommunicationB().run();
    }

    class ThreadOne extends Thread {
        @Override
        public void run() {
            synchronized (shareObject) {
                for (char i : num) {
                    System.out.print(i);
                    shareObject.notify();
                    if (first) {
                        first = false;
                        try {
                            shareObject.wait();
                        } catch (Exception e) {
                            System.out.println(e);
                        }
                    }
                }
          shareObject.notifyAll(); } } }
class ThreadTwo extends Thread { @Override public void run() { synchronized (shareObject) { for (char i : chars) { System.out.print(i); shareObject.notify(); if (!first) { first = true; try { shareObject.wait(); } catch (Exception e) { System.out.println(e); } } } }
       shareObject.notifyAll();  } } }

整体来说,实现很简单,就是锁的获取和等待来控制哪个线程运行,网上还有更多其他的实现方式,后续在继续研究

posted on 2020-06-09 18:50  翔游九天  阅读(178)  评论(0编辑  收藏  举报