首页 > 编程语言 > 详细

线程交替输入,打印

时间:2021-03-16 10:51:07      阅读:26      评论:0      收藏:0      [点我收藏+]
package com.thread;

/**
 * @author a
 * @date 2021/3/16 7:58
 * @description
 */
public class Test4 {
    static Thread t1 = null, t2 = null;
    public static void main(String[] args) {
        char[] number = "123456789".toCharArray();
        char[] letter = "ABCDEFGHI".toCharArray();
        Object o = new Object();
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : number) {
                        System.out.println(c);
                        try {
                            o.notify();
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify();
                }
                /*for (char c : number) {
                    System.out.println(c);
                    LockSupport.unpark(t2);
                    LockSupport.park();
                }*/
            }
        }, "t1");

        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (o) {
                    for (char c : letter) {
                        System.out.println(c);
                        try {
                            o.notify();
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    o.notify();
                }
                /*for (char c : letter) {
                    LockSupport.park();
                    System.out.println(c);
                    LockSupport.unpark(t1);
                }*/
            }
        }, "t2");

        t1.start();
        t2.start();
        System.out.println("=====================");
    }
}

  

线程交替输入,打印

原文:https://www.cnblogs.com/zhaoatian/p/14541283.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!