• 两个线程,一个为123456,一个为ABCDEF、交替打印出1A2B3C...


    1、使用LockSupport实现:

      

    public class T_TurnLockSupport {

    private static final char[] nums = "123456".toCharArray();
    private static final char[] chars= "ABCDEF".toCharArray();

    static Thread N=null, C=null;

    public static void main(String[] args) {

    N = new Thread(()->{
    for (char n:nums) {
    System.out.print(n);
    LockSupport.unpark(C);
    LockSupport.park();
    }
    },"N");

    C = new Thread(()->{
    for (char c:chars) {
    LockSupport.park();
    System.out.print(c);
    LockSupport.unpark(N);
    }
    },"C");

    N.start();
    C.start();
    }
    }

    2、使用wait、notify实现:
    public class T_TurnWaitNotify {

    private static final Object lock = new Object();
    private static final char[] nums = "123456789".toCharArray();
    private static final char[] chars = "ABCDEFGHI".toCharArray();

    public static void main(String[] args) {

    new Thread(()->{
    synchronized (lock){
    for (char n : nums) {
    System.out.print(n);
    try {
    lock.notify();//先唤醒另一个线程
    lock.wait();//让出锁
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    lock.notify();
    }

    }, "N").start();

    new Thread(()->{
    synchronized (lock) {
    for (char c : chars) {
    System.out.print(c);
    try {
    lock.notify();
    lock.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    lock.notify();
    }
    }, "C").start();
    }

    }
  • 相关阅读:
    GBDT(MART)
    C#中数组中Skip、Take和Concat的用法
    VUE中对获取到的数组进行排序
    el-date-picker只能选择今天
    Vue获取时间
    执行Add-Migration Initial报错
    Vue中使用for循环绑定值
    Element UI——日期时间选择器el-date-picker开始时间与结束时间约束解决方案
    el-date-picker日期组件
    缓存的问题
  • 原文地址:https://www.cnblogs.com/tengri-fighting/p/12780817.html
Copyright © 2020-2023  润新知