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

接着上次的来讲,就是用两个线程,输出1a2b3c4d5e ...

又发现了一种新的实现方式,相对来说也更简单点。

主要是通过LockSupport来实现,话不多说,上代码:

public class CommunicationC {

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

    boolean flag = true;

    ThreadOne threadOne = new ThreadOne();
    ThreadTwo threadTwo = new ThreadTwo();

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new CommunicationC().run();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void run() {
        threadOne.start();
        threadTwo.start();
    }

    class ThreadOne extends Thread {
        @Override
        public void run() {
            for (char i : num) {
                if (flag) {
                    System.out.print(i);
                    flag = false;
                    LockSupport.unpark(threadTwo);
                    LockSupport.park();
                }
            }
        }

    }

    class ThreadTwo extends Thread {
        @Override
        public void run() {
            for (char i : chars) {
                LockSupport.park();
                if (!flag) {
                    System.out.print(i);
                    flag = true;
                    LockSupport.unpark(threadOne);
                }
            }
        }
    }
}

输出结果:

 

 

通过LockSupport的park和unpark来控制线程的通信,相对来说说更简单直观点,后续还有更有趣的方式也可以放上来,以此记录下。

posted on 2020-07-01 18:29  翔游九天  阅读(139)  评论(0编辑  收藏  举报